1use crate::protocol::messages::*;
4use crate::protocol::types::*;
5use crate::session::SessionCommand;
6
7#[derive(Debug, thiserror::Error, Clone)]
9pub enum CodecError {
10 #[error("Serialization error: {0}")]
12 Serialize(String),
13 #[error("Deserialization error: {0}")]
15 Deserialize(String),
16 #[error("Invalid UTF-8")]
18 InvalidUtf8,
19}
20
21pub trait Codec: Send + Sync + 'static {
33 fn encode_setup(&self, config: &SessionConfig) -> Result<Vec<u8>, CodecError>;
35 fn encode_command(
37 &self,
38 cmd: &SessionCommand,
39 config: &SessionConfig,
40 ) -> Result<Vec<u8>, CodecError>;
41 fn decode_message(&self, data: &[u8]) -> Result<ServerMessage, CodecError>;
43}
44
45pub struct JsonCodec;
47
48impl Codec for JsonCodec {
49 fn encode_setup(&self, config: &SessionConfig) -> Result<Vec<u8>, CodecError> {
50 serde_json::to_vec(&config.to_setup_message())
51 .map_err(|e| CodecError::Serialize(e.to_string()))
52 }
53
54 fn encode_command(
55 &self,
56 cmd: &SessionCommand,
57 config: &SessionConfig,
58 ) -> Result<Vec<u8>, CodecError> {
59 match cmd {
60 SessionCommand::SendAudio(data) => {
61 let encoded = base64_simd::STANDARD.encode_to_string(data);
62 let msg = RealtimeInputMessage {
63 realtime_input: RealtimeInputPayload {
64 media_chunks: Vec::new(),
65 audio: Some(Blob {
66 mime_type: config.input_audio_format.mime_type().to_string(),
67 data: encoded,
68 }),
69 video: None,
70 audio_stream_end: None,
71 text: None,
72 },
73 };
74 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
75 }
76 SessionCommand::SendText(text) => {
77 let msg = ClientContentMessage {
78 client_content: ClientContentPayload {
79 turns: vec![Content::user(text)],
80 turn_complete: Some(true),
81 },
82 };
83 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
84 }
85 SessionCommand::SendToolResponse(responses) => {
86 let function_responses = if config.supports_async_tools() {
87 responses.clone()
88 } else {
89 responses
90 .iter()
91 .map(|r| {
92 let mut r = r.clone();
93 r.scheduling = None;
94 r
95 })
96 .collect()
97 };
98 let msg = ToolResponseMessage {
99 tool_response: ToolResponsePayload { function_responses },
100 };
101 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
102 }
103 SessionCommand::ActivityStart if config.automatic_activity_detection_enabled() => {
121 Ok(Vec::new())
122 }
123 SessionCommand::ActivityEnd if config.automatic_activity_detection_enabled() => {
124 Ok(Vec::new())
125 }
126 SessionCommand::ActivityStart => {
127 let msg = ActivitySignalMessage {
128 realtime_input: ActivitySignalPayload {
129 activity_start: Some(ActivityStart {}),
130 activity_end: None,
131 },
132 };
133 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
134 }
135 SessionCommand::ActivityEnd => {
136 let msg = ActivitySignalMessage {
137 realtime_input: ActivitySignalPayload {
138 activity_start: None,
139 activity_end: Some(ActivityEnd {}),
140 },
141 };
142 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
143 }
144 SessionCommand::SendClientContent {
145 turns,
146 turn_complete,
147 } => {
148 let msg = ClientContentMessage {
149 client_content: ClientContentPayload {
150 turns: turns.clone(),
151 turn_complete: Some(*turn_complete),
152 },
153 };
154 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
155 }
156 SessionCommand::SendVideo(data) => {
157 let encoded = base64_simd::STANDARD.encode_to_string(data);
158 let msg = RealtimeInputMessage {
159 realtime_input: RealtimeInputPayload {
160 media_chunks: Vec::new(),
161 audio: None,
162 video: Some(Blob {
163 mime_type: "image/jpeg".to_string(),
164 data: encoded,
165 }),
166 audio_stream_end: None,
167 text: None,
168 },
169 };
170 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
171 }
172 SessionCommand::UpdateInstruction(instruction) => {
177 let (role, text) = if config.supports_system_role_updates() {
178 (Role::System, instruction.clone())
179 } else {
180 (
181 Role::User,
182 format!(
183 "System instruction update, which replaces your previous \
184 instructions: {instruction}"
185 ),
186 )
187 };
188 let msg = ClientContentMessage {
189 client_content: ClientContentPayload {
190 turns: vec![Content {
191 role: Some(role),
192 parts: vec![Part::Text { text }],
193 }],
194 turn_complete: Some(false),
195 },
196 };
197 serde_json::to_vec(&msg).map_err(|e| CodecError::Serialize(e.to_string()))
198 }
199 SessionCommand::UpdateContext(update) if update.is_empty() => Ok(Vec::new()),
202 SessionCommand::UpdateContext(_) if !config.supports_context_update() => {
207 Err(CodecError::Serialize(format!(
208 "{} does not accept contextUpdate; declare the tools at setup instead",
209 config.resolved_model()
210 )))
211 }
212 SessionCommand::UpdateContext(update) => {
213 serde_json::to_vec(&config.to_context_update_message(update))
214 .map_err(|e| CodecError::Serialize(e.to_string()))
215 }
216 SessionCommand::Disconnect => Ok(Vec::new()),
217 }
218 }
219
220 fn decode_message(&self, data: &[u8]) -> Result<ServerMessage, CodecError> {
221 let text = std::str::from_utf8(data).map_err(|_| CodecError::InvalidUtf8)?;
222 ServerMessage::parse(text).map_err(|e| CodecError::Deserialize(e.to_string()))
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
234 fn simd_base64_matches_standard_engine() {
235 use base64::Engine as _;
236 let engine = &base64::engine::general_purpose::STANDARD;
237 for len in 0..300usize {
238 let bytes: Vec<u8> = (0..len).map(|i| (i * 131 + len) as u8).collect();
239 let encoded = base64_simd::STANDARD.encode_to_string(&bytes);
240 assert_eq!(encoded, engine.encode(&bytes), "encode, {len} bytes");
241 assert_eq!(
242 base64_simd::STANDARD.decode_to_vec(&encoded).unwrap(),
243 bytes,
244 "decode, {len} bytes"
245 );
246 }
247 for bad in [
249 "AAE", "AA=A", "AA E", "AA\nAA==", "-_8=", "AAE!", "====", "A===",
250 "AB==", "AAB=",
252 ] {
253 assert!(engine.decode(bad).is_err(), "engine accepts {bad:?}");
254 assert!(
255 base64_simd::STANDARD.decode_to_vec(bad).is_err(),
256 "simd accepts {bad:?}"
257 );
258 }
259 }
260
261 fn test_config() -> SessionConfig {
262 SessionConfig::new("test-key")
263 .model(ModelId::from_static("models/gemini-2.0-flash-live-001"))
264 .voice(Voice::Puck)
265 }
266
267 #[test]
272 fn json_codec_encode_setup() {
273 let codec = JsonCodec;
274 let config = test_config();
275 let bytes = codec.encode_setup(&config).unwrap();
276 let json = String::from_utf8(bytes).unwrap();
277 assert!(json.contains("\"setup\""), "should contain setup key");
278 assert!(
279 json.contains("gemini-2.0-flash-live-001"),
280 "should contain model name"
281 );
282 }
283
284 #[test]
285 fn json_codec_encode_send_text() {
286 let codec = JsonCodec;
287 let config = test_config();
288 let cmd = SessionCommand::SendText("Hello, world!".to_string());
289 let bytes = codec.encode_command(&cmd, &config).unwrap();
290 let json = String::from_utf8(bytes).unwrap();
291 assert!(
292 json.contains("\"clientContent\""),
293 "should contain clientContent"
294 );
295 assert!(
296 json.contains("Hello, world!"),
297 "should contain the text payload"
298 );
299 assert!(
300 json.contains("\"turnComplete\""),
301 "should contain turnComplete"
302 );
303 }
304
305 #[test]
306 fn json_codec_encode_send_audio() {
307 let codec = JsonCodec;
308 let config = test_config();
309 let audio_data = vec![1u8, 2, 3, 4];
310 let cmd = SessionCommand::SendAudio(audio_data.into());
311 let bytes = codec.encode_command(&cmd, &config).unwrap();
312 let json = String::from_utf8(bytes).unwrap();
313 assert!(
314 json.contains("\"realtimeInput\""),
315 "should contain realtimeInput"
316 );
317 assert!(json.contains("\"audio\""), "should contain audio field");
318 assert!(
319 json.contains("audio/pcm"),
320 "should contain the audio mime type"
321 );
322 assert!(
324 json.contains("AQIDBA=="),
325 "should contain base64-encoded data"
326 );
327 }
328
329 #[test]
330 fn json_codec_encode_tool_response() {
331 let codec = JsonCodec;
332 let config = test_config();
333 let cmd = SessionCommand::SendToolResponse(vec![FunctionResponse {
334 name: "get_weather".to_string(),
335 response: serde_json::json!({"temp": 22}),
336 id: Some("call-1".to_string()),
337 scheduling: None,
338 }]);
339 let bytes = codec.encode_command(&cmd, &config).unwrap();
340 let json = String::from_utf8(bytes).unwrap();
341 assert!(
342 json.contains("\"toolResponse\""),
343 "should contain toolResponse"
344 );
345 assert!(
346 json.contains("\"functionResponses\""),
347 "should contain functionResponses"
348 );
349 assert!(
350 json.contains("get_weather"),
351 "should contain the function name"
352 );
353 }
354
355 #[test]
356 fn json_codec_strips_scheduling_for_vertex() {
357 let codec = JsonCodec;
358 let config = SessionConfig::from_vertex("proj", "us-central1", "token")
359 .model(ModelId::from_static("models/gemini-2.0-flash-live-001"));
360 let cmd = SessionCommand::SendToolResponse(vec![FunctionResponse {
361 name: "search".to_string(),
362 response: serde_json::json!({"ok": true}),
363 id: Some("call-1".to_string()),
364 scheduling: Some(FunctionResponseScheduling::WhenIdle),
365 }]);
366 let bytes = codec.encode_command(&cmd, &config).unwrap();
367 let json = String::from_utf8(bytes).unwrap();
368 assert!(
369 !json.contains("scheduling"),
370 "Vertex AI should strip scheduling from tool responses"
371 );
372 }
373
374 #[test]
375 fn json_codec_preserves_scheduling_for_google_ai() {
376 let codec = JsonCodec;
377 let config = test_config();
378 let cmd = SessionCommand::SendToolResponse(vec![FunctionResponse {
379 name: "search".to_string(),
380 response: serde_json::json!({"ok": true}),
381 id: Some("call-1".to_string()),
382 scheduling: Some(FunctionResponseScheduling::WhenIdle),
383 }]);
384 let bytes = codec.encode_command(&cmd, &config).unwrap();
385 let json = String::from_utf8(bytes).unwrap();
386 assert!(
387 json.contains("WHEN_IDLE"),
388 "Google AI should preserve scheduling in tool responses"
389 );
390 }
391
392 #[test]
393 fn manual_activity_signals_are_suppressed_under_automatic_detection() {
394 let codec = JsonCodec;
399 let config = test_config();
400 assert!(config.automatic_activity_detection_enabled());
401
402 for cmd in [SessionCommand::ActivityStart, SessionCommand::ActivityEnd] {
403 let bytes = codec.encode_command(&cmd, &config).unwrap();
404 assert!(
405 bytes.is_empty(),
406 "explicit activity control must not reach the wire while the \
407 server is detecting activity itself; got {:?}",
408 String::from_utf8_lossy(&bytes)
409 );
410 }
411 }
412
413 #[test]
414 fn manual_activity_signals_are_sent_when_automatic_detection_is_off() {
415 let codec = JsonCodec;
416 let mut config = test_config();
417 config.realtime_input_config = Some(crate::protocol::types::RealtimeInputConfig {
418 automatic_activity_detection: Some(
419 crate::protocol::types::AutomaticActivityDetection {
420 disabled: Some(true),
421 start_of_speech_sensitivity: None,
422 end_of_speech_sensitivity: None,
423 prefix_padding_ms: None,
424 silence_duration_ms: None,
425 },
426 ),
427 activity_handling: None,
428 turn_coverage: None,
429 });
430 assert!(!config.automatic_activity_detection_enabled());
431
432 let json = String::from_utf8(
433 codec
434 .encode_command(&SessionCommand::ActivityStart, &config)
435 .unwrap(),
436 )
437 .unwrap();
438 assert!(json.contains("\"activityStart\""), "{json}");
439 assert!(!json.contains("\"activityEnd\""), "{json}");
440
441 let json = String::from_utf8(
442 codec
443 .encode_command(&SessionCommand::ActivityEnd, &config)
444 .unwrap(),
445 )
446 .unwrap();
447 assert!(json.contains("\"activityEnd\""), "{json}");
448 assert!(!json.contains("\"activityStart\""), "{json}");
449 }
450
451 #[test]
452 fn json_codec_encode_client_content() {
453 let codec = JsonCodec;
454 let config = test_config();
455 let cmd = SessionCommand::SendClientContent {
456 turns: vec![Content::user("context message")],
457 turn_complete: false,
458 };
459 let bytes = codec.encode_command(&cmd, &config).unwrap();
460 let json = String::from_utf8(bytes).unwrap();
461 assert!(
462 json.contains("\"clientContent\""),
463 "should contain clientContent"
464 );
465 assert!(
466 json.contains("context message"),
467 "should contain the text content"
468 );
469 assert!(
470 json.contains("\"turnComplete\":false"),
471 "should contain turnComplete set to false"
472 );
473 }
474
475 #[test]
476 fn json_codec_encode_send_video() {
477 let codec = JsonCodec;
478 let config = test_config();
479 let cmd = SessionCommand::SendVideo(vec![0xFF, 0xD8, 0xFF].into()); let bytes = codec.encode_command(&cmd, &config).unwrap();
481 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
482 assert_eq!(
483 json["realtimeInput"]["video"]["mimeType"].as_str().unwrap(),
484 "image/jpeg"
485 );
486 assert!(json["realtimeInput"]["video"]["data"].is_string());
487 }
488
489 #[test]
490 fn json_codec_encode_update_instruction_google_ai() {
491 let codec = JsonCodec;
494 let config = test_config();
495 assert!(!config.supports_system_role_updates());
496 let cmd = SessionCommand::UpdateInstruction("New instruction".into());
497 let bytes = codec.encode_command(&cmd, &config).unwrap();
498 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
499 let turns = &json["clientContent"]["turns"];
500 assert_eq!(turns[0]["role"], "user");
501 let text = turns[0]["parts"][0]["text"].as_str().unwrap();
502 assert!(text.starts_with("System instruction update"), "{text}");
503 assert!(text.ends_with("New instruction"), "{text}");
504 assert_eq!(json["clientContent"]["turnComplete"], false);
505 }
506
507 #[test]
508 fn json_codec_encode_update_instruction_vertex() {
509 let codec = JsonCodec;
510 let config = SessionConfig::from_vertex("p", "us-central1", "t");
511 let cmd = SessionCommand::UpdateInstruction("New instruction".into());
512 let bytes = codec.encode_command(&cmd, &config).unwrap();
513 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
514 let turns = &json["clientContent"]["turns"];
515 assert_eq!(turns[0]["role"], "system");
516 assert_eq!(turns[0]["parts"][0]["text"], "New instruction");
517 assert_eq!(json["clientContent"]["turnComplete"], false);
518 }
519
520 fn decl(name: &str) -> FunctionDeclaration {
521 FunctionDeclaration {
522 name: name.into(),
523 description: format!("{name} tool"),
524 parameters: None,
525 behavior: Some(FunctionCallingBehavior::NonBlocking),
526 }
527 }
528
529 fn encode_update(config: &SessionConfig, update: ContextUpdate) -> serde_json::Value {
530 let bytes = JsonCodec
531 .encode_command(&SessionCommand::UpdateContext(update), config)
532 .unwrap();
533 serde_json::from_slice(&bytes).unwrap()
534 }
535
536 #[test]
537 fn json_codec_encode_context_update_replaces_both() {
538 let config = SessionConfig::from_vertex("p", "us-central1", "t").model(ModelId::LIVE_3_8);
539 let json = encode_update(
540 &config,
541 ContextUpdate::new()
542 .system_instruction("Verified caller.")
543 .tools(vec![Tool::functions(vec![decl("get_balance")])]),
544 );
545 let update = &json["contextUpdate"];
546 assert_eq!(
547 update["systemInstruction"]["parts"][0]["text"],
548 "Verified caller."
549 );
550 let decls = &update["tools"]["tools"][0]["functionDeclarations"];
551 assert_eq!(decls[0]["name"], "get_balance");
552 assert_eq!(decls[0]["behavior"], "NON_BLOCKING");
554 }
555
556 #[test]
557 fn json_codec_encode_context_update_presence_semantics() {
558 let config = SessionConfig::new("k").model(ModelId::LIVE_3_8);
559
560 let json = encode_update(&config, ContextUpdate::new().system_instruction("x"));
562 assert!(json["contextUpdate"].get("tools").is_none(), "{json}");
563
564 let json = encode_update(&config, ContextUpdate::new().tools(vec![]));
565 assert!(
566 json["contextUpdate"].get("systemInstruction").is_none(),
567 "{json}"
568 );
569 assert_eq!(
571 json["contextUpdate"]["tools"]["tools"],
572 serde_json::json!([])
573 );
574 }
575
576 #[test]
577 fn context_update_shapes_tools_like_setup() {
578 let config = SessionConfig::from_vertex("p", "us-central1", "t")
581 .model(ModelId::LIVE_2_5_FLASH_NATIVE_AUDIO);
582 assert!(!config.supports_async_tools());
583 let message = config.to_context_update_message(
584 &ContextUpdate::new().tools(vec![Tool::functions(vec![decl("f")])]),
585 );
586 let decls = message.context_update.tools.unwrap().tools[0]
587 .function_declarations
588 .clone()
589 .unwrap();
590 assert_eq!(decls[0].behavior, None);
591 }
592
593 #[test]
594 fn json_codec_empty_context_update_sends_nothing() {
595 for model in [ModelId::LIVE_3_8, ModelId::FLASH_2_5_NATIVE_AUDIO_LATEST] {
598 let config = SessionConfig::new("k").model(model);
599 let bytes = JsonCodec
600 .encode_command(
601 &SessionCommand::UpdateContext(ContextUpdate::new()),
602 &config,
603 )
604 .unwrap();
605 assert!(
606 bytes.is_empty(),
607 "an empty update must not reset the prefix cache"
608 );
609 }
610 }
611
612 #[test]
613 fn json_codec_refuses_context_update_on_models_without_it() {
614 for config in [
616 SessionConfig::new("k").model(ModelId::FLASH_2_5_NATIVE_AUDIO_LATEST),
617 SessionConfig::from_vertex("p", "us-central1", "t")
618 .model(ModelId::LIVE_2_5_FLASH_NATIVE_AUDIO),
619 ] {
620 assert!(!config.supports_context_update());
621 let err = JsonCodec
622 .encode_command(
623 &SessionCommand::UpdateContext(ContextUpdate::new().system_instruction("x")),
624 &config,
625 )
626 .unwrap_err();
627 assert!(
628 err.to_string().contains("does not accept contextUpdate"),
629 "{err}"
630 );
631 }
632 }
633
634 #[test]
635 fn context_update_is_available_on_3_8_live_on_both_platforms() {
636 for model in [ModelId::LIVE_3_8, ModelId::LIVE_3_8_EXTENDED_THINKING] {
637 assert!(
638 SessionConfig::new("k")
639 .model(model.clone())
640 .supports_context_update()
641 );
642 assert!(
643 SessionConfig::from_vertex("p", "us-central1", "t")
644 .model(model)
645 .supports_context_update()
646 );
647 }
648 }
649
650 #[test]
651 fn json_codec_encode_disconnect() {
652 let codec = JsonCodec;
653 let config = test_config();
654 let cmd = SessionCommand::Disconnect;
655 let bytes = codec.encode_command(&cmd, &config).unwrap();
656 assert!(bytes.is_empty(), "Disconnect should produce empty bytes");
657 }
658
659 #[test]
664 fn json_codec_decode_setup_complete() {
665 let codec = JsonCodec;
666 let json = r#"{"setupComplete":{"sessionResumption":{"handle":"abc123"}}}"#;
667 let msg = codec.decode_message(json.as_bytes()).unwrap();
668 match msg {
669 ServerMessage::SetupComplete(sc) => {
670 let handle = sc.setup_complete.session_resumption.unwrap().handle;
671 assert_eq!(handle, Some("abc123".to_string()));
672 }
673 _ => panic!("Expected SetupComplete"),
674 }
675 }
676
677 #[test]
678 fn json_codec_decode_server_content() {
679 let codec = JsonCodec;
680 let json = r#"{
681 "serverContent": {
682 "modelTurn": {
683 "parts": [{"text": "Hello! How can I help?"}]
684 },
685 "turnComplete": true
686 }
687 }"#;
688 let msg = codec.decode_message(json.as_bytes()).unwrap();
689 match msg {
690 ServerMessage::ServerContent(sc) => {
691 assert!(sc.server_content.turn_complete.unwrap_or(false));
692 let turn = sc.server_content.model_turn.unwrap();
693 assert_eq!(turn.parts.len(), 1);
694 match &turn.parts[0] {
695 Part::Text { text } => assert_eq!(text, "Hello! How can I help?"),
696 _ => panic!("Expected text part"),
697 }
698 }
699 _ => panic!("Expected ServerContent"),
700 }
701 }
702
703 #[test]
704 fn json_codec_decode_tool_call() {
705 let codec = JsonCodec;
706 let json = r#"{
707 "toolCall": {
708 "functionCalls": [
709 {"name": "get_weather", "args": {"city": "London"}, "id": "call-1"}
710 ]
711 }
712 }"#;
713 let msg = codec.decode_message(json.as_bytes()).unwrap();
714 match msg {
715 ServerMessage::ToolCall(tc) => {
716 assert_eq!(tc.tool_call.function_calls.len(), 1);
717 assert_eq!(tc.tool_call.function_calls[0].name, "get_weather");
718 }
719 _ => panic!("Expected ToolCall"),
720 }
721 }
722
723 #[test]
724 fn json_codec_decode_invalid_utf8() {
725 let codec = JsonCodec;
726 let bad_bytes: &[u8] = &[0xFF, 0xFE, 0xFD];
727 let result = codec.decode_message(bad_bytes);
728 match result {
729 Err(CodecError::InvalidUtf8) => {} other => panic!("Expected CodecError::InvalidUtf8, got {other:?}"),
731 }
732 }
733}