deepgram 0.14.0

Community Rust SDK for Deepgram's automated speech recognition APIs.
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Client-to-server message types for the Voice Agent WebSocket.
//!
//! Mirrors `AgentV1*Message` schemas in
//! `asyncapi/schemas/schemas.agent.v1.yml`. Eight are dynamic-control
//! messages sent during a session (`UpdateListen`, `UpdateSpeak`,
//! `UpdateThink`, `UpdatePrompt`, `InjectUserMessage`,
//! `InjectAgentMessage`, `FunctionCallResponse`, `ForceEndTurn`); one is
//! a connection keep-alive (`KeepAlive`); the tenth (`Settings`) is
//! defined in [`crate::agent::settings`] and is the only message that can
//! carry the agent's full configuration.
//!
//! [`ClientMessage`] wraps all ten as a discriminated union. Wire
//! discrimination is structural via each variant's own `type` field
//! (modeled as a single-variant marker enum); on the Rust side serde
//! [`#[serde(untagged)]`](serde::Deserialize) tries each variant in
//! turn and accepts whichever matches the JSON's `type`.
//!
//! Note: `FunctionCallResponseMessage` is bidirectional in the spec —
//! the same wire shape appears as both a client→server message and a
//! server→client event. The struct defined here is reused by the
//! server-emitted event in [`crate::agent::response`].

use serde::{Deserialize, Serialize};

use crate::agent::listen::AgentListenSettings;
use crate::agent::settings::SettingsMessage;
use crate::agent::speak::SpeakSettings;
use crate::agent::think::ThinkSettings;

/// Discriminated union of all ten client-to-server JSON messages.
///
/// Audio frames sent by the client are binary WebSocket frames and are
/// therefore not part of this enum — they're handled by the connection
/// layer (separate from JSON dispatch).
//
// `Settings` carries the full agent configuration (~312 bytes) while
// `KeepAlive` is essentially empty. The disparity is intentional: each
// variant is constructed and immediately serialized (or deserialized
// and immediately matched), never stored long-term, so boxing the
// larger variants would add a heap allocation per WebSocket send for no
// observable benefit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
pub enum ClientMessage {
    /// Initial / re-issued configuration for the session.
    Settings(SettingsMessage),
    /// Swap the Listen provider (model, language hints, EOT thresholds,
    /// keyterms) mid-session.
    UpdateListen(UpdateListenMessage),
    /// Swap the Speak provider mid-session.
    UpdateSpeak(UpdateSpeakMessage),
    /// Swap the Think provider mid-session.
    UpdateThink(UpdateThinkMessage),
    /// Replace the system prompt mid-session.
    UpdatePrompt(UpdatePromptMessage),
    /// Inject a synthetic user utterance into the conversation.
    InjectUserMessage(InjectUserMessageMessage),
    /// Trigger an agent utterance immediately.
    InjectAgentMessage(InjectAgentMessageMessage),
    /// Reply to a server `FunctionCallRequest` (client-side function execution).
    FunctionCallResponse(FunctionCallResponseMessage),
    /// Keep the WebSocket alive between user turns.
    KeepAlive(KeepAliveMessage),
    /// End the current user turn immediately (Flux STT listen providers only).
    ForceEndTurn(ForceEndTurnMessage),
}

impl ClientMessage {
    /// Convenience: wrap a `SettingsMessage`.
    pub fn settings(message: SettingsMessage) -> Self {
        Self::Settings(message)
    }

    /// Convenience: build an `UpdateListen` message.
    pub fn update_listen(listen: AgentListenSettings) -> Self {
        Self::UpdateListen(UpdateListenMessage::new(listen))
    }

    /// Convenience: a `ForceEndTurn` message.
    pub fn force_end_turn() -> Self {
        Self::ForceEndTurn(ForceEndTurnMessage::default())
    }

    /// Convenience: build a one-variant `UpdateSpeak` message.
    pub fn update_speak_one(speak: SpeakSettings) -> Self {
        Self::UpdateSpeak(UpdateSpeakMessage::one(speak))
    }

    /// Convenience: build a multi-variant `UpdateSpeak` message.
    pub fn update_speak_many(speak: impl IntoIterator<Item = SpeakSettings>) -> Self {
        Self::UpdateSpeak(UpdateSpeakMessage::many(speak))
    }

    /// Convenience: build a one-variant `UpdateThink` message.
    pub fn update_think_one(think: ThinkSettings) -> Self {
        Self::UpdateThink(UpdateThinkMessage::one(think))
    }

    /// Convenience: build a multi-variant `UpdateThink` message.
    pub fn update_think_many(think: impl IntoIterator<Item = ThinkSettings>) -> Self {
        Self::UpdateThink(UpdateThinkMessage::many(think))
    }

    /// Convenience: build an `UpdatePrompt` message.
    pub fn update_prompt(prompt: impl Into<String>) -> Self {
        Self::UpdatePrompt(UpdatePromptMessage::new(prompt))
    }

    /// Convenience: build an `InjectUserMessage`.
    pub fn inject_user_message(content: impl Into<String>) -> Self {
        Self::InjectUserMessage(InjectUserMessageMessage::new(content))
    }

    /// Convenience: build an `InjectAgentMessage` with the default behavior.
    pub fn inject_agent_message(message: impl Into<String>) -> Self {
        Self::InjectAgentMessage(InjectAgentMessageMessage::new(message))
    }

    /// Convenience: build a `FunctionCallResponse`.
    pub fn function_call_response(name: impl Into<String>, content: impl Into<String>) -> Self {
        Self::FunctionCallResponse(FunctionCallResponseMessage::new(name, content))
    }

    /// Convenience: a `KeepAlive` message.
    pub fn keep_alive() -> Self {
        Self::KeepAlive(KeepAliveMessage::default())
    }
}

// ---------- UpdateListen ----------

/// Marker for the `"UpdateListen"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum UpdateListenType {
    /// Always serializes as `"UpdateListen"`.
    #[default]
    UpdateListen,
}

/// Mirrors `AgentV1UpdateListenMessage` — change the Listen configuration
/// mid-session.
///
/// The payload uses the same shape as `agent.listen` in `Settings`: a
/// `provider` object. Model and language can be changed for any provider;
/// keyterms and the end-of-turn thresholds can only be updated mid-session
/// for Flux STT (V2) models. The server confirms with `ListenUpdated`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct UpdateListenMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: UpdateListenType,

    /// New Listen configuration (`listen.provider`).
    pub listen: AgentListenSettings,
}

impl UpdateListenMessage {
    /// Construct with the given Listen configuration.
    pub fn new(listen: AgentListenSettings) -> Self {
        Self {
            message_type: UpdateListenType::default(),
            listen,
        }
    }
}

// ---------- UpdateSpeak ----------

/// Marker for the `"UpdateSpeak"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum UpdateSpeakType {
    /// Always serializes as `"UpdateSpeak"`.
    #[default]
    UpdateSpeak,
}

/// Mirrors `AgentV1UpdateSpeakMessage` — change the Speak provider mid-session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct UpdateSpeakMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: UpdateSpeakType,

    /// New Speak configuration. Single value or array on the wire; modeled
    /// as `Vec<SpeakSettings>` with custom serde so a one-element vec
    /// serializes as a scalar object.
    #[serde(
        serialize_with = "serialize_speak_one_or_many",
        deserialize_with = "deserialize_speak_one_or_many"
    )]
    pub speak: Vec<SpeakSettings>,
}

impl UpdateSpeakMessage {
    /// Construct with a single Speak provider.
    pub fn one(speak: SpeakSettings) -> Self {
        Self {
            message_type: UpdateSpeakType::default(),
            speak: vec![speak],
        }
    }

    /// Construct with an array of Speak providers.
    pub fn many(speak: impl IntoIterator<Item = SpeakSettings>) -> Self {
        Self {
            message_type: UpdateSpeakType::default(),
            speak: speak.into_iter().collect(),
        }
    }
}

// ---------- UpdateThink ----------

/// Marker for the `"UpdateThink"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum UpdateThinkType {
    /// Always serializes as `"UpdateThink"`.
    #[default]
    UpdateThink,
}

/// Mirrors `AgentV1UpdateThinkMessage` — change the Think provider mid-session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct UpdateThinkMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: UpdateThinkType,

    /// New Think configuration. Single value or array on the wire; modeled
    /// as `Vec<ThinkSettings>` with custom serde so a one-element vec
    /// serializes as a scalar object.
    #[serde(
        serialize_with = "serialize_think_one_or_many",
        deserialize_with = "deserialize_think_one_or_many"
    )]
    pub think: Vec<ThinkSettings>,
}

impl UpdateThinkMessage {
    /// Construct with a single Think provider.
    pub fn one(think: ThinkSettings) -> Self {
        Self {
            message_type: UpdateThinkType::default(),
            think: vec![think],
        }
    }

    /// Construct with an array of Think providers.
    pub fn many(think: impl IntoIterator<Item = ThinkSettings>) -> Self {
        Self {
            message_type: UpdateThinkType::default(),
            think: think.into_iter().collect(),
        }
    }
}

// ---------- UpdatePrompt ----------

/// Marker for the `"UpdatePrompt"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum UpdatePromptType {
    /// Always serializes as `"UpdatePrompt"`.
    #[default]
    UpdatePrompt,
}

/// Mirrors `AgentV1UpdatePromptMessage` — replace the system prompt mid-session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct UpdatePromptMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: UpdatePromptType,

    /// New system prompt.
    pub prompt: String,
}

impl UpdatePromptMessage {
    /// Construct with the given prompt.
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            message_type: UpdatePromptType::default(),
            prompt: prompt.into(),
        }
    }
}

// ---------- InjectUserMessage ----------

/// Marker for the `"InjectUserMessage"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum InjectUserMessageType {
    /// Always serializes as `"InjectUserMessage"`.
    #[default]
    InjectUserMessage,
}

/// Mirrors `AgentV1InjectUserMessageMessage` — inject a synthetic user
/// utterance into the conversation. The agent will respond as if the
/// user had spoken `content`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InjectUserMessageMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: InjectUserMessageType,

    /// The phrase the agent should respond to.
    pub content: String,
}

impl InjectUserMessageMessage {
    /// Construct with the given content.
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            message_type: InjectUserMessageType::default(),
            content: content.into(),
        }
    }
}

// ---------- InjectAgentMessage ----------

/// Marker for the `"InjectAgentMessage"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum InjectAgentMessageType {
    /// Always serializes as `"InjectAgentMessage"`.
    #[default]
    InjectAgentMessage,
}

/// Behavior knob on `InjectAgentMessage` — controls how injection
/// interacts with any in-progress turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum InjectAgentBehavior {
    /// Speak only if neither the user nor the agent is mid-turn. If a
    /// turn is in progress, the server replies with `InjectionRefused`.
    #[default]
    Default,
    /// Append the message after any queued `ConversationText` without
    /// interrupting the current turn or think response. If nothing is
    /// queued, the message plays immediately.
    Queue,
    /// Speak immediately. If the agent was already speaking, the current
    /// speech is cut off and replaced with the new message. If the user is
    /// speaking, the agent interrupts them — but the user's continued
    /// speech triggers `UserStartedSpeaking`, which quickly interrupts the
    /// agent again.
    Interrupt,
}

/// Mirrors `AgentV1InjectAgentMessageMessage` — make the agent speak an
/// arbitrary line.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InjectAgentMessageMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: InjectAgentMessageType,

    /// What the agent should say.
    pub message: String,

    /// How the injection interacts with any in-progress turn.
    /// Defaults to [`InjectAgentBehavior::Default`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub behavior: Option<InjectAgentBehavior>,
}

impl InjectAgentMessageMessage {
    /// Construct with the given utterance and the default behavior.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message_type: InjectAgentMessageType::default(),
            message: message.into(),
            behavior: None,
        }
    }

    /// Override the behavior.
    pub fn with_behavior(mut self, behavior: InjectAgentBehavior) -> Self {
        self.behavior = Some(behavior);
        self
    }
}

// ---------- FunctionCallResponse ----------

/// Marker for the `"FunctionCallResponse"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum FunctionCallResponseType {
    /// Always serializes as `"FunctionCallResponse"`.
    #[default]
    FunctionCallResponse,
}

/// Mirrors `AgentV1FunctionCallResponseMessage` — bidirectional
/// function-call result.
///
/// In the **client → server** direction this responds to a server-emitted
/// `FunctionCallRequest` for a client-side function: `id` should match
/// the request's `id`. In the **server → client** direction it reports
/// the result of a server-side function execution; the server may omit
/// `id` when it doesn't track an internal request ID.
///
/// `name` and `content` are required in both directions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FunctionCallResponseMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: FunctionCallResponseType,

    /// Identifier matching the originating `FunctionCallRequest`. Required
    /// for client responses; the server may omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// Function name.
    pub name: String,

    /// Function result payload (opaque string per spec — typically a
    /// JSON-encoded blob).
    pub content: String,
}

impl FunctionCallResponseMessage {
    /// Construct without an `id` (suitable for server-emitted responses).
    pub fn new(name: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            message_type: FunctionCallResponseType::default(),
            id: None,
            name: name.into(),
            content: content.into(),
        }
    }

    /// Construct with an explicit `id` (required for client → server use).
    pub fn with_id(
        id: impl Into<String>,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        Self {
            message_type: FunctionCallResponseType::default(),
            id: Some(id.into()),
            name: name.into(),
            content: content.into(),
        }
    }
}

// ---------- KeepAlive ----------

/// Marker for the `"KeepAlive"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum KeepAliveType {
    /// Always serializes as `"KeepAlive"`.
    #[default]
    KeepAlive,
}

/// Mirrors `AgentV1ControlMessage` (`type: "KeepAlive"`).
///
/// The server closes connections that go silent. While the client is not
/// sending audio, send one `KeepAlive` every 8 seconds to hold the
/// session open; it is not needed while audio is streaming. `KeepAlive`
/// does not extend the 2-hour maximum session length.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct KeepAliveMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: KeepAliveType,
}

// ---------- ForceEndTurn ----------

/// Marker for the `"ForceEndTurn"` discriminator value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ForceEndTurnType {
    /// Always serializes as `"ForceEndTurn"`.
    #[default]
    ForceEndTurn,
}

/// Mirrors `AgentV1ForceEndTurnMessage` — end the current user turn
/// immediately, without waiting for end-of-turn detection.
///
/// Requires a Deepgram V2 (Flux STT) listen provider. With any other listen
/// provider the server replies with a `FORCE_END_TURN_UNSUPPORTED`
/// `Warning` and the turn does not end. Pair with
/// `eot_threshold: 1.0` on the listen provider to take full control of
/// turn boundaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForceEndTurnMessage {
    #[serde(rename = "type", default)]
    #[allow(missing_docs)]
    pub message_type: ForceEndTurnType,
}

// ---------- one-or-many serde helpers ----------

fn serialize_speak_one_or_many<S>(values: &[SpeakSettings], ser: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    if values.len() == 1 {
        values[0].serialize(ser)
    } else {
        values.serialize(ser)
    }
}

fn deserialize_speak_one_or_many<'de, D>(de: D) -> Result<Vec<SpeakSettings>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    // See note in `crate::agent::settings` re: `large_enum_variant`.
    #[derive(Deserialize)]
    #[serde(untagged)]
    #[allow(clippy::large_enum_variant)]
    enum OneOrMany {
        Many(Vec<SpeakSettings>),
        One(SpeakSettings),
    }
    Ok(match OneOrMany::deserialize(de)? {
        OneOrMany::One(x) => vec![x],
        OneOrMany::Many(v) => v,
    })
}

fn serialize_think_one_or_many<S>(values: &[ThinkSettings], ser: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    if values.len() == 1 {
        values[0].serialize(ser)
    } else {
        values.serialize(ser)
    }
}

fn deserialize_think_one_or_many<'de, D>(de: D) -> Result<Vec<ThinkSettings>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    #[allow(clippy::large_enum_variant)]
    enum OneOrMany {
        Many(Vec<ThinkSettings>),
        One(ThinkSettings),
    }
    Ok(match OneOrMany::deserialize(de)? {
        OneOrMany::One(x) => vec![x],
        OneOrMany::Many(v) => v,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::audio::{AudioConfig, AudioInput, AudioInputEncoding};
    use crate::agent::listen::{
        AgentListenProvider, AgentListenSettings, DeepgramListenV2Provider,
    };
    use crate::agent::settings::{AgentConfig, InlineAgentConfig};
    use crate::agent::speak::{
        DeepgramSpeakExpressivity, DeepgramSpeakModel, DeepgramSpeakProvider, SpeakProvider,
        SpeakSettings,
    };
    use crate::agent::think::{OpenAiModel, OpenAiThinkProvider, ThinkProvider};
    use serde_json::json;

    fn sample_speak() -> SpeakSettings {
        SpeakSettings::new(SpeakProvider::Deepgram(DeepgramSpeakProvider::new(
            DeepgramSpeakModel::Aura2ThaliaEn,
        )))
    }

    fn sample_think() -> ThinkSettings {
        ThinkSettings::new(ThinkProvider::OpenAi(OpenAiThinkProvider::new(
            OpenAiModel::Gpt4oMini,
        )))
    }

    #[test]
    fn update_speak_one_round_trip() {
        let raw = json!({
            "type": "UpdateSpeak",
            "speak": {
                "provider": {
                    "type": "deepgram",
                    "model": "aura-2-thalia-en"
                }
            }
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(msg, ClientMessage::UpdateSpeak(_)));
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn update_speak_many_round_trip() {
        let raw = json!({
            "type": "UpdateSpeak",
            "speak": [
                { "provider": { "type": "deepgram", "model": "aura-asteria-en" } },
                { "provider": { "type": "deepgram", "model": "aura-2-luna-en" } }
            ]
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::UpdateSpeak(m) = &msg {
            assert_eq!(m.speak.len(), 2);
        } else {
            panic!("expected UpdateSpeak");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn update_speak_with_flux_tts_expressivity_exact_wire_json() {
        // `expressivity` rides `UpdateSpeak` in the same JSON-integer form
        // it takes in `Settings`.
        let msg = ClientMessage::update_speak_one(SpeakSettings::new(SpeakProvider::Deepgram(
            DeepgramSpeakProvider::v2(DeepgramSpeakModel::FluxAlexisEn)
                .with_speed(1.05)
                .with_expressivity(DeepgramSpeakExpressivity::NegativeTwo),
        )));
        assert_eq!(
            serde_json::to_string(&msg).unwrap(),
            concat!(
                r#"{"type":"UpdateSpeak","speak":{"provider":{"type":"deepgram","#,
                r#""version":"v2","model":"flux-alexis-en","speed":1.05,"expressivity":-2}}}"#,
            )
        );
        let value = serde_json::to_value(&msg).unwrap();
        assert!(value["speak"]["provider"]["expressivity"].is_number());

        // Deserialization also accepts the string form the AsyncAPI
        // declares, and normalizes it to the same typed value.
        let quoted = json!({
            "type": "UpdateSpeak",
            "speak": { "provider": {
                "type": "deepgram",
                "version": "v2",
                "model": "flux-alexis-en",
                "speed": 1.05,
                "expressivity": "-2"
            }}
        });
        assert_eq!(
            serde_json::from_value::<ClientMessage>(quoted).unwrap(),
            msg
        );
    }

    #[test]
    fn update_listen_exact_wire_json() {
        let msg = ClientMessage::update_listen(AgentListenSettings::new(
            AgentListenProvider::DeepgramV2(
                DeepgramListenV2Provider::new("flux-general-multi")
                    .with_language_hints(["en", "es"])
                    .with_eot_threshold(1.0)
                    .with_keyterms(["Deepgram"]),
            ),
        ));
        assert_eq!(
            serde_json::to_string(&msg).unwrap(),
            r#"{"type":"UpdateListen","listen":{"provider":{"type":"deepgram","version":"v2","model":"flux-general-multi","language_hints":["en","es"],"eot_threshold":1.0,"keyterms":["Deepgram"]}}}"#
        );
    }

    #[test]
    fn update_listen_round_trip() {
        let raw = json!({
            "type": "UpdateListen",
            "listen": {
                "provider": {
                    "type": "deepgram",
                    "version": "v1",
                    "model": "nova-3",
                    "language": "en-US"
                }
            }
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        match &msg {
            ClientMessage::UpdateListen(m) => {
                assert_eq!(m.message_type, UpdateListenType::UpdateListen);
                assert!(matches!(
                    m.listen.provider,
                    AgentListenProvider::DeepgramV1(_)
                ));
            }
            other => panic!("expected UpdateListen, got {other:?}"),
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn force_end_turn_exact_wire_json() {
        assert_eq!(
            serde_json::to_string(&ForceEndTurnMessage::default()).unwrap(),
            r#"{"type":"ForceEndTurn"}"#
        );
        let raw = json!({ "type": "ForceEndTurn" });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(msg, ClientMessage::ForceEndTurn(_)));
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
        assert_eq!(
            serde_json::to_value(ClientMessage::force_end_turn()).unwrap(),
            raw
        );
    }

    #[test]
    fn update_think_round_trip() {
        let raw = json!({
            "type": "UpdateThink",
            "think": {
                "provider": {
                    "type": "open_ai",
                    "model": "gpt-4o"
                }
            }
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(msg, ClientMessage::UpdateThink(_)));
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn update_prompt_round_trip() {
        let raw = json!({
            "type": "UpdatePrompt",
            "prompt": "You are now in customer-support mode."
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::UpdatePrompt(m) = &msg {
            assert_eq!(m.prompt, "You are now in customer-support mode.");
        } else {
            panic!("expected UpdatePrompt");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn inject_user_message_round_trip() {
        let raw = json!({
            "type": "InjectUserMessage",
            "content": "What's the weather?"
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(msg, ClientMessage::InjectUserMessage(_)));
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn inject_agent_message_default_behavior() {
        let raw = json!({
            "type": "InjectAgentMessage",
            "message": "Sorry, I missed that."
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::InjectAgentMessage(m) = &msg {
            assert_eq!(m.message, "Sorry, I missed that.");
            assert!(m.behavior.is_none());
        } else {
            panic!("expected InjectAgentMessage");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn inject_agent_message_queue_behavior() {
        let raw = json!({
            "type": "InjectAgentMessage",
            "message": "By the way, business hours are 9-5.",
            "behavior": "queue"
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::InjectAgentMessage(m) = &msg {
            assert_eq!(m.behavior, Some(InjectAgentBehavior::Queue));
        } else {
            panic!("expected InjectAgentMessage");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn inject_agent_message_interrupt_behavior() {
        let raw = json!({
            "type": "InjectAgentMessage",
            "message": "One moment — transferring you now.",
            "behavior": "interrupt"
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::InjectAgentMessage(m) = &msg {
            assert_eq!(m.behavior, Some(InjectAgentBehavior::Interrupt));
        } else {
            panic!("expected InjectAgentMessage");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);

        let built = InjectAgentMessageMessage::new("One moment — transferring you now.")
            .with_behavior(InjectAgentBehavior::Interrupt);
        assert_eq!(
            serde_json::to_string(&built).unwrap(),
            r#"{"type":"InjectAgentMessage","message":"One moment — transferring you now.","behavior":"interrupt"}"#
        );
    }

    #[test]
    fn function_call_response_with_id_round_trip() {
        let raw = json!({
            "type": "FunctionCallResponse",
            "id": "func_42",
            "name": "get_weather",
            "content": "{\"temp\": 72}"
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::FunctionCallResponse(m) = &msg {
            assert_eq!(m.id.as_deref(), Some("func_42"));
            assert_eq!(m.name, "get_weather");
        } else {
            panic!("expected FunctionCallResponse");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn function_call_response_without_id_round_trip() {
        let raw = json!({
            "type": "FunctionCallResponse",
            "name": "internal_lookup",
            "content": "[{\"id\": 1}]"
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        if let ClientMessage::FunctionCallResponse(m) = &msg {
            assert!(m.id.is_none());
        } else {
            panic!("expected FunctionCallResponse");
        }
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn keep_alive_round_trip() {
        let raw = json!({ "type": "KeepAlive" });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(msg, ClientMessage::KeepAlive(_)));
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn settings_dispatched_through_client_message() {
        // Sanity: the existing SettingsMessage routes through the
        // untagged enum's first arm.
        let raw = json!({
            "type": "Settings",
            "audio": {
                "input": { "encoding": "linear16", "sample_rate": 16000 }
            },
            "agent": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
        });
        let msg: ClientMessage = serde_json::from_value(raw.clone()).unwrap();
        assert!(matches!(msg, ClientMessage::Settings(_)));
        assert_eq!(serde_json::to_value(&msg).unwrap(), raw);
    }

    #[test]
    fn unknown_type_does_not_match_any_variant() {
        let raw = json!({ "type": "MysteryMessage", "x": 1 });
        let err = serde_json::from_value::<ClientMessage>(raw).unwrap_err();
        // Untagged dispatch produces a generic error pointing at the
        // last attempted variant; exact message shape is serde-internal.
        // We just want to make sure deserialization fails cleanly.
        let s = err.to_string();
        assert!(!s.is_empty());
    }

    #[test]
    fn convenience_constructors() {
        // Exercise the helpers on ClientMessage so they actually compile.
        let _ = ClientMessage::settings(crate::agent::SettingsMessage::new(
            AudioConfig::new(
                Some(AudioInput::new(AudioInputEncoding::Linear16, 16_000)),
                None,
            ),
            AgentConfig::inline(InlineAgentConfig::from_parts(
                AgentListenSettings::new(AgentListenProvider::DeepgramV2(
                    DeepgramListenV2Provider::new("flux-general-en"),
                )),
                sample_think(),
                sample_speak(),
            )),
        ));
        let _ = ClientMessage::update_speak_one(sample_speak());
        let _ = ClientMessage::update_speak_many([sample_speak(), sample_speak()]);
        let _ = ClientMessage::update_think_one(sample_think());
        let _ = ClientMessage::update_think_many([sample_think()]);
        let _ = ClientMessage::update_prompt("hi");
        let _ = ClientMessage::inject_user_message("hi");
        let _ = ClientMessage::inject_agent_message("hi");
        let _ = ClientMessage::function_call_response("fn", "{}");
        let _ = ClientMessage::keep_alive();
        let _ = ClientMessage::update_listen(AgentListenSettings::new(
            AgentListenProvider::DeepgramV2(DeepgramListenV2Provider::new("flux-general-en")),
        ));
        let _ = ClientMessage::force_end_turn();
    }

    #[test]
    fn inject_agent_with_behavior_builder() {
        let m = InjectAgentMessageMessage::new("hi").with_behavior(InjectAgentBehavior::Queue);
        let v = serde_json::to_value(&m).unwrap();
        assert_eq!(v["behavior"], "queue");
    }

    #[test]
    fn function_call_response_with_id_builder() {
        let m = FunctionCallResponseMessage::with_id("f1", "fn", "{}");
        assert_eq!(m.id.as_deref(), Some("f1"));
    }

    #[test]
    fn behavior_default_is_default() {
        assert_eq!(InjectAgentBehavior::default(), InjectAgentBehavior::Default);
    }
}