1pub mod authoring;
24mod code;
25mod codegen;
26mod decisions;
27pub mod project;
28mod simulate;
29mod skills;
30pub mod store;
31
32pub use code::{CodeLimitsSpec, CodeSpec, schema_shape, value_shape};
33pub use decisions::{BooleanCriteriaSpec, DecisionKind, DecisionSpec};
34pub use project::{ProjectFile, ProjectLanguage, ProjectOptions, SdkSource};
35pub use store::{BundleRef, BundleStore, BundleVersion, StoreError, open_store};
36
37pub use skills::{
38 SkillSpec, SkillToolSpec, TaskExpectation, TaskObservationKind, TaskScenario, TaskStep,
39 TaskTraceSnapshot,
40};
41
42pub use simulate::{
43 SimEvent, SimSnapshot, SpecTest, TestExpectation, TestReport, TestStepResult, trace_test,
44};
45
46use std::collections::BTreeMap;
47use std::sync::Arc;
48
49use serde::{Deserialize, Serialize};
50use serde_json::{Value, json};
51
52use gemini_adk_rs::expr::Expr;
53use gemini_adk_rs::flow::{Constraint, Flow, Guard, Pred, Step};
54use gemini_adk_rs::live::extractor::{ExtractionTrigger, FieldPromotion, LlmExtractor};
55use gemini_adk_rs::live::{ContextDelivery, RepairConfig, SteeringMode};
56use gemini_adk_rs::llm::BaseLlm;
57use gemini_adk_rs::state::State;
58use gemini_adk_rs::tool::{SimpleTool, ToolDispatcher, ToolFunction};
59use gemini_genai_rs::prelude::{
60 AutomaticActivityDetection, Content, FunctionResponseScheduling, Sensitivity, SessionWriter,
61 Voice,
62};
63
64use crate::compose::tools::T;
65use crate::live::Live;
66
67#[derive(
69 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
70)]
71#[serde(rename_all = "lowercase")]
72pub enum SpecModality {
73 #[default]
75 Text,
76 Audio,
78}
79
80#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
87pub struct HttpBinding {
88 #[serde(default = "default_method")]
90 pub method: String,
91 pub url: String,
93 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
95 pub headers: BTreeMap<String, String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub body: Option<Value>,
99 #[serde(skip)]
102 #[schemars(skip)]
103 pub(crate) reach: Option<BindingAllowlist>,
104}
105
106fn default_method() -> String {
107 "GET".to_string()
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
117pub struct ToolSpec {
118 pub name: String,
120 #[serde(default)]
122 pub description: String,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub parameters: Option<Value>,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub response: Option<Value>,
129 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub returns: Option<Value>,
134 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
136 pub set_state: BTreeMap<String, Value>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub save_response_as: Option<String>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub http: Option<HttpBinding>,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub mcp: Option<String>,
150 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
154 pub background: bool,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub scheduling: Option<SchedulingSpec>,
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
162#[serde(rename_all = "snake_case")]
163pub enum SchedulingSpec {
164 Interrupt,
166 WhenIdle,
168 Silent,
170}
171
172impl SchedulingSpec {
173 fn to_wire(self) -> FunctionResponseScheduling {
174 match self {
175 SchedulingSpec::Interrupt => FunctionResponseScheduling::Interrupt,
176 SchedulingSpec::WhenIdle => FunctionResponseScheduling::WhenIdle,
177 SchedulingSpec::Silent => FunctionResponseScheduling::Silent,
178 }
179 }
180}
181
182#[derive(
184 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
185)]
186#[serde(rename_all = "snake_case")]
187pub enum PromotePolicy {
188 #[default]
190 KeepKnown,
191 Overwrite,
193 TrueOnly,
195 NonEmpty,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
202pub struct PromoteSpec {
203 pub field: String,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub to: Option<String>,
208 #[serde(default)]
210 pub policy: PromotePolicy,
211}
212
213impl PromoteSpec {
214 fn target(&self) -> &str {
215 self.to.as_deref().unwrap_or(&self.field)
216 }
217
218 fn to_rule(&self) -> FieldPromotion {
219 let rule = match self.policy {
220 PromotePolicy::KeepKnown => FieldPromotion::keep_known(&self.field),
221 PromotePolicy::Overwrite => FieldPromotion::overwrite(&self.field),
222 PromotePolicy::TrueOnly => FieldPromotion::true_only(&self.field),
223 PromotePolicy::NonEmpty => FieldPromotion::non_empty(&self.field),
224 };
225 match &self.to {
226 Some(key) => rule.to(key),
227 None => rule,
228 }
229 }
230}
231
232#[derive(
234 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
235)]
236#[serde(rename_all = "snake_case")]
237pub enum TriggerSpec {
238 #[default]
240 EveryTurn,
241 AfterToolCall,
243 OnGenerationComplete,
245 OnPhaseChange,
247}
248
249impl TriggerSpec {
250 fn to_trigger(self) -> ExtractionTrigger {
251 match self {
252 TriggerSpec::EveryTurn => ExtractionTrigger::EveryTurn,
253 TriggerSpec::AfterToolCall => ExtractionTrigger::AfterToolCall,
254 TriggerSpec::OnGenerationComplete => ExtractionTrigger::OnGenerationComplete,
255 TriggerSpec::OnPhaseChange => ExtractionTrigger::OnPhaseChange,
256 }
257 }
258}
259
260#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
265pub struct ExtractSpec {
266 pub name: String,
268 pub instruction: String,
270 pub schema: Value,
272 #[serde(default = "default_window")]
274 pub window: usize,
275 #[serde(default)]
277 pub trigger: TriggerSpec,
278 #[serde(default, skip_serializing_if = "Vec::is_empty")]
280 pub promote: Vec<PromoteSpec>,
281 #[serde(default, skip_serializing_if = "Option::is_none")]
284 pub model: Option<String>,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub thinking_budget: Option<u32>,
289}
290
291pub const RECOMMENDED_EXTRACTION_MODEL: &str = "gemini-3.5-flash-lite";
298
299pub const RECOMMENDED_EXTRACTION_THINKING_BUDGET: u32 =
302 gemini_adk_rs::live::extractor::FALLBACK_THINKING_BUDGET;
303
304const UNPINNED_EXTRACTION_WARNING: &str = "extraction names no model, so it runs on the host \
306 default (gemini-flash-latest, a rolling alias whose model and latency change under you, \
307 unless GEMINI_TEXT_MODEL is set); every turn waits for it: set models.extraction";
308
309#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
311pub struct ModelsSpec {
312 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub extraction: Option<String>,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub extraction_thinking_budget: Option<u32>,
324}
325
326fn default_window() -> usize {
327 3
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
334#[serde(rename_all = "snake_case")]
335pub enum EffectSpec {
336 Set(BTreeMap<String, Value>),
338 Context(String),
341 Prompt(String),
344 Remember(String),
347}
348
349#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
355pub struct TransitionSpec {
356 pub to: String,
358 pub when: Guard,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
362 pub description: Option<String>,
363}
364
365#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
367pub struct PhaseSpec {
368 pub name: String,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub instruction: Option<String>,
373 #[serde(default, skip_serializing_if = "Vec::is_empty")]
375 pub tools: Vec<String>,
376 #[serde(default, skip_serializing_if = "Vec::is_empty")]
378 pub needs: Vec<String>,
379 #[serde(default, skip_serializing_if = "Vec::is_empty")]
381 pub on_enter: Vec<EffectSpec>,
382 #[serde(default, skip_serializing_if = "Vec::is_empty")]
384 pub transitions: Vec<TransitionSpec>,
385 #[serde(default, skip_serializing_if = "Option::is_none")]
387 pub prompt_on_enter: Option<bool>,
388 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
390 pub terminal: bool,
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
395#[serde(rename_all = "snake_case")]
396pub enum WatchCondition {
397 Changed,
399 ChangedTo(Value),
401 CrossedAbove(f64),
403 CrossedBelow(f64),
405 BecameTrue,
407 BecameFalse,
409}
410
411#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
416pub struct WatchSpec {
417 pub key: String,
419 pub condition: WatchCondition,
421 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
423 pub set: BTreeMap<String, Value>,
424 #[serde(default, skip_serializing_if = "Vec::is_empty")]
426 pub effects: Vec<EffectSpec>,
427}
428
429#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
436pub struct PatternSpec {
437 pub name: String,
439 pub when: Guard,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
443 pub sustained_secs: Option<u64>,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
446 pub turns: Option<u32>,
447 #[serde(default, skip_serializing_if = "Vec::is_empty")]
449 pub effects: Vec<EffectSpec>,
450}
451
452#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
459pub struct ComputedSpec {
460 pub key: String,
462 pub from: Expr,
464 #[serde(default, skip_serializing_if = "String::is_empty")]
466 pub description: String,
467}
468
469#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
471#[serde(rename_all = "snake_case")]
472pub enum StateType {
473 Boolean,
475 Number,
477 String,
479 Object,
481 Array,
483}
484
485impl StateType {
486 fn matches(self, value: &Value) -> bool {
487 matches!(
488 (self, value),
489 (StateType::Boolean, Value::Bool(_))
490 | (StateType::Number, Value::Number(_))
491 | (StateType::String, Value::String(_))
492 | (StateType::Object, Value::Object(_))
493 | (StateType::Array, Value::Array(_))
494 )
495 }
496}
497
498#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
505pub struct StateFieldSpec {
506 #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
508 pub kind: Option<StateType>,
509 #[serde(default, skip_serializing_if = "String::is_empty")]
511 pub description: String,
512 #[serde(default, skip_serializing_if = "Option::is_none")]
514 pub default: Option<Value>,
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
522pub struct MemorySlotSpec {
523 pub predicate: String,
525 pub to: String,
527}
528
529#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
536pub struct MemorySpec {
537 #[serde(default, skip_serializing_if = "Vec::is_empty")]
539 pub slots: Vec<MemorySlotSpec>,
540}
541
542#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
544#[serde(rename_all = "snake_case")]
545pub enum SensitivitySpec {
546 Low,
548 Medium,
550 High,
552}
553
554impl SensitivitySpec {
555 fn to_wire(self) -> Sensitivity {
556 match self {
557 SensitivitySpec::Low => Sensitivity::SensitivityLow,
558 SensitivitySpec::Medium => Sensitivity::SensitivityMedium,
559 SensitivitySpec::High => Sensitivity::SensitivityHigh,
560 }
561 }
562}
563
564#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
567pub struct VadSpec {
568 #[serde(default, skip_serializing_if = "Option::is_none")]
570 pub start_sensitivity: Option<SensitivitySpec>,
571 #[serde(default, skip_serializing_if = "Option::is_none")]
573 pub end_sensitivity: Option<SensitivitySpec>,
574 #[serde(default, skip_serializing_if = "Option::is_none")]
576 pub prefix_padding_ms: Option<u32>,
577 #[serde(default, skip_serializing_if = "Option::is_none")]
579 pub silence_duration_ms: Option<u32>,
580}
581
582#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
588pub struct AudioSpec {
589 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub denoise: Option<bool>,
593 #[serde(default, skip_serializing_if = "Option::is_none")]
596 pub noise_gate: Option<NoiseGateSpec>,
597 #[serde(default, skip_serializing_if = "Option::is_none")]
600 pub client_vad: Option<ClientVadSpec>,
601 #[serde(default, skip_serializing_if = "Option::is_none")]
603 pub authority: Option<AuthoritySpec>,
604 #[serde(default, skip_serializing_if = "Option::is_none")]
608 pub eot_hold_ms: Option<u32>,
609 #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub min_interruption_ms: Option<u32>,
614}
615
616#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
618pub struct NoiseGateSpec {
619 #[serde(default = "default_gate_threshold")]
622 pub threshold_rms: f64,
623 #[serde(default = "default_gate_hold")]
625 pub hold_frames: u32,
626}
627
628fn default_gate_threshold() -> f64 {
629 700.0
630}
631fn default_gate_hold() -> u32 {
632 3
633}
634
635#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
637pub struct ClientVadSpec {
638 #[serde(default, skip_serializing_if = "Option::is_none")]
640 pub preset: Option<ClientVadPreset>,
641 #[serde(default, skip_serializing_if = "Option::is_none")]
643 pub start_threshold_db: Option<f64>,
644 #[serde(default, skip_serializing_if = "Option::is_none")]
646 pub stop_threshold_db: Option<f64>,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub min_speech_frames: Option<u32>,
650 #[serde(default, skip_serializing_if = "Option::is_none")]
652 pub hangover_frames: Option<u32>,
653}
654
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
657#[serde(rename_all = "snake_case")]
658pub enum ClientVadPreset {
659 Default,
661 NoisyStreet,
664}
665
666impl ClientVadSpec {
667 pub fn to_config(&self) -> gemini_genai_rs::vad::VadConfig {
669 let mut config = match self.preset {
670 Some(ClientVadPreset::NoisyStreet) => gemini_genai_rs::vad::VadConfig::noisy_street(),
671 _ => gemini_genai_rs::vad::VadConfig::default(),
672 };
673 if let Some(v) = self.start_threshold_db {
674 config.start_threshold_db = v;
675 }
676 if let Some(v) = self.stop_threshold_db {
677 config.stop_threshold_db = v;
678 }
679 if let Some(v) = self.min_speech_frames {
680 config.min_speech_frames = v;
681 }
682 if let Some(v) = self.hangover_frames {
683 config.hangover_frames = v;
684 }
685 config
686 }
687}
688
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
692#[serde(rename_all = "snake_case")]
693pub enum AuthoritySpec {
694 Server,
696 Client,
699}
700
701#[derive(Debug, Clone, Copy, Serialize, Deserialize, schemars::JsonSchema)]
703pub struct TranscriptionSpec {
704 #[serde(default = "default_true")]
706 pub input: bool,
707 #[serde(default = "default_true")]
709 pub output: bool,
710}
711
712fn default_true() -> bool {
713 true
714}
715
716#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
718#[serde(rename_all = "snake_case")]
719pub enum SteeringSpec {
720 InstructionUpdate,
722 ContextInjection,
724 Hybrid,
726 ContextUpdate,
730}
731
732#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
734#[serde(rename_all = "snake_case")]
735pub enum ContextDeliverySpec {
736 Immediate,
738 Deferred,
740}
741
742#[derive(Debug, Clone, Copy, Serialize, Deserialize, schemars::JsonSchema)]
744pub struct RepairSpec {
745 pub nudge_after: u32,
747 pub escalate_after: u32,
749}
750
751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
753#[serde(rename_all = "snake_case")]
754pub enum PersistenceSpec {
755 Fs {
757 dir: String,
759 },
760 Memory,
762}
763
764#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
769pub struct RuntimeSpec {
770 #[serde(
772 default,
773 skip_serializing_if = "Option::is_none",
774 serialize_with = "serialize_f32_exact"
775 )]
776 pub temperature: Option<f32>,
777 #[serde(default, skip_serializing_if = "Option::is_none")]
779 pub thinking_budget: Option<u32>,
780 #[serde(default, skip_serializing_if = "Option::is_none")]
782 pub include_thoughts: Option<bool>,
783 #[serde(default, skip_serializing_if = "Option::is_none")]
785 pub transcription: Option<TranscriptionSpec>,
786 #[serde(default, skip_serializing_if = "Option::is_none")]
788 pub proactive_audio: Option<bool>,
789 #[serde(default, skip_serializing_if = "Option::is_none")]
791 pub vad: Option<VadSpec>,
792 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub audio: Option<AudioSpec>,
795 #[serde(default, skip_serializing_if = "Option::is_none")]
797 pub soft_turn_timeout_ms: Option<u64>,
798 #[serde(default, skip_serializing_if = "Option::is_none")]
800 pub steering: Option<SteeringSpec>,
801 #[serde(default, skip_serializing_if = "Option::is_none")]
803 pub context_delivery: Option<ContextDeliverySpec>,
804 #[serde(default, skip_serializing_if = "Option::is_none")]
806 pub repair: Option<RepairSpec>,
807 #[serde(default, skip_serializing_if = "Option::is_none")]
809 pub persistence: Option<PersistenceSpec>,
810 #[serde(default, skip_serializing_if = "Option::is_none")]
812 pub session_id: Option<String>,
813 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
815 pub lossy_audio: bool,
816 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
818 pub lossy_transcript: bool,
819}
820
821#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
829pub struct UseFragment {
830 pub fragment: String,
832 pub namespace: String,
834 #[serde(default, skip_serializing_if = "Vec::is_empty")]
836 pub after: Vec<String>,
837}
838
839#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
841pub struct SessionSpec {
842 #[serde(default)]
844 pub name: String,
845 #[serde(default, skip_serializing_if = "String::is_empty")]
847 pub version: String,
848 #[serde(default)]
850 pub description: String,
851 #[serde(default)]
853 pub instruction: String,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
856 pub greeting: Option<String>,
857 #[serde(default)]
859 pub modality: SpecModality,
860 #[serde(default, skip_serializing_if = "Option::is_none")]
862 pub voice: Option<String>,
863 #[serde(default, skip_serializing_if = "Vec::is_empty")]
865 pub tools: Vec<ToolSpec>,
866 #[serde(default, skip_serializing_if = "Vec::is_empty")]
869 pub mcp: Vec<String>,
870 #[serde(default, skip_serializing_if = "Vec::is_empty")]
872 pub extract: Vec<ExtractSpec>,
873 #[serde(default, skip_serializing_if = "is_default_models")]
875 pub models: ModelsSpec,
876 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
881 pub decisions: BTreeMap<String, DecisionSpec>,
882 #[serde(default, skip_serializing_if = "Option::is_none")]
886 pub code: Option<CodeSpec>,
887 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
889 pub state: BTreeMap<String, StateFieldSpec>,
890 #[serde(default, skip_serializing_if = "Vec::is_empty")]
892 pub computed: Vec<ComputedSpec>,
893 #[serde(default, skip_serializing_if = "Option::is_none")]
897 pub memory: Option<MemorySpec>,
898 #[serde(default, skip_serializing_if = "Option::is_none")]
900 pub runtime: Option<RuntimeSpec>,
901 #[serde(default, skip_serializing_if = "Vec::is_empty")]
903 pub phases: Vec<PhaseSpec>,
904 #[serde(default, skip_serializing_if = "Option::is_none")]
906 pub initial_phase: Option<String>,
907 #[serde(default, skip_serializing_if = "Vec::is_empty")]
909 pub watch: Vec<WatchSpec>,
910 #[serde(default, skip_serializing_if = "Vec::is_empty")]
912 pub patterns: Vec<PatternSpec>,
913 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
915 pub fragments: BTreeMap<String, Flow>,
916 #[serde(default, skip_serializing_if = "Vec::is_empty")]
918 pub use_fragments: Vec<UseFragment>,
919 #[serde(default, skip_serializing_if = "Option::is_none")]
921 pub flow: Option<Flow>,
922 #[serde(default, skip_serializing_if = "Option::is_none")]
927 pub conversation: Option<crate::conversation::ConversationSpec>,
928 #[serde(default, skip_serializing_if = "Vec::is_empty")]
930 pub skills: Vec<SkillSpec>,
931 #[serde(default, skip_serializing_if = "Vec::is_empty")]
933 pub task_scenarios: Vec<TaskScenario>,
934 #[serde(default, skip_serializing_if = "Vec::is_empty")]
937 pub scenarios: Vec<crate::simulation::Scenario>,
938 #[serde(default, skip_serializing_if = "Vec::is_empty")]
941 pub tests: Vec<SpecTest>,
942}
943
944#[derive(Debug, Clone, Serialize)]
946pub struct SpecValidation {
947 pub valid: bool,
949 pub errors: Vec<String>,
951 pub warnings: Vec<String>,
953 pub mermaid: String,
955 pub tools: Vec<String>,
957 pub steps: usize,
959}
960
961pub trait MemoryBinding: Send + Sync {
971 fn install(&self, live: Live, memory: &MemorySpec) -> Live;
973 fn remember(&self, note: String);
976 fn task_memory(
979 &self,
980 _memory: &MemorySpec,
981 ) -> Result<Arc<dyn gemini_adk_rs::tasks::TaskMemoryService>, String> {
982 Err("this memory binding does not support task-owned memory services".into())
983 }
984 fn task_tools(&self) -> Vec<Arc<dyn ToolFunction>> {
987 Vec::new()
988 }
989 fn install_task_lifecycle(&self, live: Live) -> Live {
992 live
993 }
994}
995
996#[derive(Debug, Clone, Default, PartialEq, Eq)]
1008pub struct BindingAllowlist {
1009 http_prefixes: Vec<String>,
1010 mcp: Vec<String>,
1011}
1012
1013impl BindingAllowlist {
1014 pub fn allow_http_prefix(mut self, prefix: impl Into<String>) -> Self {
1018 let mut prefix = prefix.into();
1019 let after_scheme = prefix.split_once("://").map_or("", |(_, rest)| rest);
1020 if !after_scheme.contains('/') {
1021 prefix.push('/');
1022 }
1023 self.http_prefixes.push(prefix);
1024 self
1025 }
1026
1027 pub fn allow_mcp(mut self, params: impl Into<String>) -> Self {
1029 self.mcp.push(params.into());
1030 self
1031 }
1032
1033 fn allows_http(&self, url: &str) -> bool {
1038 let Ok(target) = url::Url::parse(url) else {
1039 return false;
1040 };
1041 if !target.username().is_empty() || target.password().is_some() {
1042 return false;
1043 }
1044 self.http_prefixes.iter().any(|prefix| {
1045 url::Url::parse(prefix).is_ok_and(|prefix| {
1046 prefix.scheme() == target.scheme()
1047 && prefix.host() == target.host()
1048 && prefix.port_or_known_default() == target.port_or_known_default()
1049 && target.path().starts_with(prefix.path())
1050 })
1051 })
1052 }
1053
1054 fn allows_mcp(&self, params: &str) -> bool {
1055 self.mcp.iter().any(|m| m.trim() == params.trim())
1056 }
1057}
1058
1059const RUNTIME_WRITTEN: [&str; 6] = [
1062 "flow:",
1063 "session:",
1064 "verbatim:",
1065 "correction:",
1066 "repair:",
1067 "telephony:",
1068];
1069
1070#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1072pub struct ScenarioReport {
1073 pub name: String,
1075 pub passed: bool,
1077 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 pub error: Option<String>,
1080}
1081
1082pub const MEMORY_TOOL_NAMES: [&str; 2] = ["recall_context", "manage_memory"];
1084
1085#[derive(Default, Clone)]
1088pub struct SpecResources {
1089 pub extraction_llm: Option<Arc<dyn BaseLlm>>,
1092 pub models: Option<Arc<gemini_adk_rs::llm::LlmRegistry>>,
1098 pub decision_model: Option<Arc<dyn gemini_adk_rs::decision::DecisionModel>>,
1102 pub memory: Option<Arc<dyn MemoryBinding>>,
1105 pub code_sandbox: Option<Arc<dyn gemini_adk_rs::code_mode::CodeSandbox>>,
1109 pub tools: BTreeMap<String, Arc<dyn ToolFunction>>,
1115}
1116
1117impl SpecResources {
1118 pub fn implement_skill(mut self, skill: &str, tool: impl ToolFunction + 'static) -> Self {
1120 self.tools
1121 .insert(format!("{skill}/{}", tool.name()), Arc::new(tool));
1122 self
1123 }
1124
1125 pub fn implement(mut self, tool: impl ToolFunction + 'static) -> Self {
1127 self.tools.insert(tool.name().to_string(), Arc::new(tool));
1128 self
1129 }
1130}
1131
1132fn serialize_f32_exact<S: serde::Serializer>(
1136 value: &Option<f32>,
1137 serializer: S,
1138) -> Result<S::Ok, S::Error> {
1139 use serde::Serialize as _;
1140 match value {
1141 Some(v) => {
1142 let widened: f64 = v.to_string().parse().unwrap_or(f64::from(*v));
1145 widened.serialize(serializer)
1146 }
1147 None => serializer.serialize_none(),
1148 }
1149}
1150
1151fn is_default_models(models: &ModelsSpec) -> bool {
1152 *models == ModelsSpec::default()
1153}
1154
1155fn resolve_model(
1158 name: &str,
1159 resources: &SpecResources,
1160 cache: &mut BTreeMap<String, Arc<dyn BaseLlm>>,
1161) -> Result<Arc<dyn BaseLlm>, String> {
1162 if let Some(llm) = cache.get(name) {
1163 return Ok(llm.clone());
1164 }
1165 let llm = match resources.models.as_ref().and_then(|r| r.resolve(name)) {
1166 Some(llm) => llm,
1167 None if name.starts_with("gemini") || name.starts_with("models/gemini") => Arc::new(
1168 gemini_adk_rs::llm::GeminiLlm::try_new(gemini_adk_rs::llm::GeminiLlmParams {
1169 model: Some(name.to_string()),
1170 ..Default::default()
1171 })
1172 .map_err(|e| format!("model '{name}': {e}"))?,
1173 )
1174 as Arc<dyn BaseLlm>,
1175 None => {
1176 return Err(format!(
1177 "model '{name}': nothing resolves it; register it in SpecResources.models"
1178 ));
1179 }
1180 };
1181 cache.insert(name.to_string(), llm.clone());
1182 Ok(llm)
1183}
1184
1185pub(crate) fn extraction_llm_for(
1188 entry: &ExtractSpec,
1189 default: Option<&str>,
1190 resources: &SpecResources,
1191 cache: &mut BTreeMap<String, Arc<dyn BaseLlm>>,
1192) -> Result<Arc<dyn BaseLlm>, String> {
1193 match entry.model.as_deref().or(default) {
1194 Some(name) => resolve_model(name, resources, cache)
1195 .map_err(|e| format!("extract '{}': {e}", entry.name)),
1196 None => resources.extraction_llm.clone().ok_or_else(|| {
1197 format!(
1198 "extract '{}' names no model and SpecResources.extraction_llm is not set; \
1199 set models.extraction",
1200 entry.name
1201 )
1202 }),
1203 }
1204}
1205
1206impl SessionSpec {
1207 pub fn uses_default_extraction_model(&self) -> bool {
1210 let unnamed = |entries: &[ExtractSpec], default: Option<&str>| {
1211 default.is_none() && entries.iter().any(|e| e.model.is_none())
1212 };
1213 unnamed(&self.extract, self.models.extraction.as_deref())
1214 || self
1215 .skills
1216 .iter()
1217 .any(|skill| unnamed(&skill.extract, self.models.extraction.as_deref()))
1218 }
1219
1220 pub fn requires_extraction(&self) -> bool {
1222 !self.extract.is_empty()
1223 || self.conversation.as_ref().is_some_and(|conversation| {
1224 conversation
1225 .stages
1226 .iter()
1227 .chain(
1228 conversation
1229 .overlays
1230 .iter()
1231 .flat_map(|overlay| &overlay.stages),
1232 )
1233 .any(|stage| stage.frame.is_some())
1234 })
1235 || self.skills.iter().any(|skill| {
1236 !skill.extract.is_empty()
1237 || skill.conversation.as_ref().is_some_and(|conversation| {
1238 conversation
1239 .stages
1240 .iter()
1241 .chain(
1242 conversation
1243 .overlays
1244 .iter()
1245 .flat_map(|overlay| &overlay.stages),
1246 )
1247 .any(|stage| stage.frame.is_some())
1248 })
1249 })
1250 }
1251
1252 pub fn requires_memory(&self) -> bool {
1254 self.memory.is_some() || self.skills.iter().any(|skill| skill.memory.is_some())
1255 }
1256
1257 pub fn from_value(value: Value) -> Result<Self, String> {
1260 let is_bare_flow = value.get("flow").is_none() && value.get("steps").is_some();
1261 if is_bare_flow {
1262 let flow: Flow =
1263 serde_json::from_value(value).map_err(|e| format!("invalid flow JSON: {e}"))?;
1264 return Ok(Self {
1265 flow: Some(flow),
1266 ..Self::default()
1267 });
1268 }
1269 serde_json::from_value(value).map_err(|e| format!("invalid session spec JSON: {e}"))
1270 }
1271
1272 pub fn json_schema() -> Value {
1275 serde_json::to_value(schemars::schema_for!(SessionSpec)).unwrap_or_else(|_| json!({}))
1276 }
1277
1278 pub fn tool_names(&self) -> Vec<String> {
1280 self.tools.iter().map(|t| t.name.clone()).collect()
1281 }
1282
1283 pub fn effective_flow(&self) -> Result<Flow, Vec<String>> {
1285 if let Some(conversation) = &self.conversation {
1286 if self.flow.is_some() || !self.use_fragments.is_empty() {
1287 return Err(vec![
1288 "set either `conversation` or `flow` (with `use_fragments`), not both".into(),
1289 ]);
1290 }
1291 return crate::conversation::Conversation::from_spec_stubbing_resolvers(
1292 conversation.clone(),
1293 )
1294 .map(|compiled| compiled.flow().flow().clone())
1295 .map_err(|e| vec![format!("conversation: {e}")]);
1296 }
1297 let mut flow = self.flow.clone().unwrap_or_default();
1298 let mut errors = Vec::new();
1299 for use_frag in &self.use_fragments {
1300 match self.fragments.get(&use_frag.fragment) {
1301 Some(fragment) => {
1302 splice_fragment(&mut flow, fragment, use_frag, &mut errors);
1303 }
1304 None => errors.push(format!(
1305 "use_fragments references unknown fragment '{}'",
1306 use_frag.fragment
1307 )),
1308 }
1309 }
1310 if errors.is_empty() {
1311 Ok(flow)
1312 } else {
1313 Err(errors)
1314 }
1315 }
1316
1317 pub fn state_keys_written(&self) -> std::collections::BTreeSet<String> {
1321 let mut keys = std::collections::BTreeSet::new();
1322 for t in &self.tools {
1323 keys.extend(t.set_state.keys().cloned());
1324 keys.extend(t.save_response_as.iter().cloned());
1325 }
1326 for e in &self.extract {
1327 keys.insert(e.name.clone());
1328 for p in &e.promote {
1329 keys.insert(p.target().to_string());
1330 }
1331 }
1332 keys.extend(self.decisions.values().filter_map(|d| d.writes.clone()));
1333 for p in &self.phases {
1334 for eff in &p.on_enter {
1335 if let EffectSpec::Set(map) = eff {
1336 keys.extend(map.keys().cloned());
1337 }
1338 }
1339 }
1340 for w in &self.watch {
1341 keys.extend(w.set.keys().cloned());
1342 for eff in &w.effects {
1343 if let EffectSpec::Set(map) = eff {
1344 keys.extend(map.keys().cloned());
1345 }
1346 }
1347 }
1348 for p in &self.patterns {
1349 for eff in &p.effects {
1350 if let EffectSpec::Set(map) = eff {
1351 keys.extend(map.keys().cloned());
1352 }
1353 }
1354 }
1355 for c in &self.computed {
1356 keys.insert(c.key.clone());
1359 keys.insert(format!("derived:{}", c.key));
1360 }
1361 if let Some(memory) = &self.memory {
1362 for slot in &memory.slots {
1363 keys.extend([slot.to.clone()]);
1364 }
1365 }
1366 for (key, field) in &self.state {
1367 if field.default.is_some() {
1368 keys.insert(key.clone());
1369 }
1370 }
1371 for stage in self.conversation_stages() {
1373 keys.extend(stage.collect.iter().cloned());
1374 keys.extend(stage.resolve.iter().map(|r| r.slot.clone()));
1375 if let Some(frame) = &stage.frame {
1376 keys.extend(frame.slot_keys());
1377 }
1378 }
1379 keys
1380 }
1381
1382 fn conversation_stages(&self) -> impl Iterator<Item = &crate::conversation::StageSpec> {
1384 self.conversation.iter().flat_map(|c| {
1385 c.stages
1386 .iter()
1387 .chain(c.overlays.iter().flat_map(|o| o.stages.iter()))
1388 })
1389 }
1390
1391 fn resolver_registry(
1394 &self,
1395 tools: &[Arc<SimpleTool>],
1396 ) -> crate::conversation::ResolverRegistry {
1397 let mut registry = crate::conversation::ResolverRegistry::new();
1398 for stage in self.conversation_stages() {
1399 for resolve in &stage.resolve {
1400 let name = resolve
1401 .resolver
1402 .clone()
1403 .unwrap_or_else(|| resolve.slot.clone());
1404 if let Some(tool) = tools
1405 .iter()
1406 .find(|t| ToolFunction::name(t.as_ref()) == name)
1407 {
1408 let tool = tool.clone();
1409 registry.add(name, move |args| {
1410 let tool = tool.clone();
1411 async move {
1412 gemini_adk_rs::tool::ToolFunction::call(tool.as_ref(), args)
1413 .await
1414 .map_err(|e| e.to_string())
1415 }
1416 });
1417 }
1418 }
1419 }
1420 registry
1421 }
1422
1423 pub async fn run_scenarios(&self) -> Vec<ScenarioReport> {
1427 let failed = |error: String| -> Vec<ScenarioReport> {
1428 self.scenarios
1429 .iter()
1430 .map(|s| ScenarioReport {
1431 name: s.name.clone(),
1432 passed: false,
1433 error: Some(error.clone()),
1434 })
1435 .collect()
1436 };
1437 let Some(conversation) = &self.conversation else {
1438 return failed("the spec has no `conversation` to run against".into());
1439 };
1440 let compiled = match crate::conversation::Conversation::from_spec_stubbing_resolvers(
1441 conversation.clone(),
1442 ) {
1443 Ok(compiled) => compiled,
1444 Err(e) => return failed(format!("conversation: {e}")),
1445 };
1446 let bank: BTreeMap<String, gemini_adk_rs::decision::Decision> = self
1447 .decisions
1448 .iter()
1449 .map(|(id, d)| (id.clone(), d.compile()))
1450 .collect();
1451 let mut reports = Vec::with_capacity(self.scenarios.len());
1452 for scenario in &self.scenarios {
1453 let sim =
1454 crate::simulation::Sim::new(&compiled, gemini_adk_rs::flow::Enforcement::Enforce)
1455 .with_decisions(bank.clone());
1456 let result = scenario.run_in(sim).await;
1457 reports.push(ScenarioReport {
1458 name: scenario.name.clone(),
1459 passed: result.is_ok(),
1460 error: result.err(),
1461 });
1462 }
1463 reports
1464 }
1465
1466 fn all_effects(&self) -> Vec<(String, &EffectSpec)> {
1468 let mut out = Vec::new();
1469 for p in &self.phases {
1470 for eff in &p.on_enter {
1471 out.push((format!("phase '{}'", p.name), eff));
1472 }
1473 }
1474 for w in &self.watch {
1475 for eff in &w.effects {
1476 out.push((format!("watch '{}'", w.key), eff));
1477 }
1478 }
1479 for p in &self.patterns {
1480 for eff in &p.effects {
1481 out.push((format!("pattern '{}'", p.name), eff));
1482 }
1483 }
1484 out
1485 }
1486
1487 pub(crate) fn recompute_computed(&self, state: &State) {
1492 for _ in 0..self.computed.len() {
1493 let mut changed = false;
1494 for c in &self.computed {
1495 if let Some(value) = c.from.eval(state) {
1496 let derived = format!("derived:{}", c.key);
1497 if state.get_raw(&derived).as_ref() != Some(&value) {
1498 let _ = state.set(&derived, value);
1499 changed = true;
1500 }
1501 }
1502 }
1503 if !changed {
1504 break;
1505 }
1506 }
1507 }
1508
1509 pub(crate) fn seed_state_defaults(&self, state: &State) {
1511 for (key, field) in &self.state {
1512 if let Some(default) = &field.default
1513 && state.get_raw(key).is_none()
1514 {
1515 let _ = state.set(key, default.clone());
1516 }
1517 }
1518 }
1519
1520 pub fn validate(&self) -> SpecValidation {
1524 self.validate_with_http_support(true)
1525 }
1526
1527 pub fn validate_for_replay(&self) -> SpecValidation {
1533 self.validate_with_http_support(false)
1534 }
1535
1536 fn validate_with_http_support(&self, require_http_support: bool) -> SpecValidation {
1537 self.validate_parts(require_http_support, false, &Default::default())
1538 }
1539
1540 fn validate_definition(
1541 &self,
1542 require_http_support: bool,
1543 activation_inputs: &std::collections::BTreeSet<String>,
1544 ) -> SpecValidation {
1545 self.validate_parts(require_http_support, true, activation_inputs)
1546 }
1547
1548 fn validate_parts(
1549 &self,
1550 require_http_support: bool,
1551 allow_ungoverned: bool,
1552 activation_inputs: &std::collections::BTreeSet<String>,
1553 ) -> SpecValidation {
1554 let mut errors = Vec::new();
1555 let mut warnings = Vec::new();
1556 let mut skill_tools = Vec::new();
1557 let mut skill_steps = 0;
1558 let mut written = self.state_keys_written();
1559 written.extend(activation_inputs.iter().cloned());
1560
1561 if !self.skills.is_empty() {
1562 if self.flow.is_some()
1563 || self.conversation.is_some()
1564 || !self.phases.is_empty()
1565 || !self.tools.is_empty()
1566 || !self.mcp.is_empty()
1567 || !self.extract.is_empty()
1568 || !self.decisions.is_empty()
1569 || !self.computed.is_empty()
1570 || !self.watch.is_empty()
1571 || !self.patterns.is_empty()
1572 || !self.use_fragments.is_empty()
1573 || self.memory.is_some()
1574 || !self.state.is_empty()
1575 {
1576 errors.push("skills own their state, tools and governance; do not combine them with a session-level pipeline".into());
1577 }
1578 let mut names = std::collections::BTreeSet::new();
1579 for skill in &self.skills {
1580 if !names.insert(&skill.name) {
1581 errors.push(format!(
1582 "skill '{}' is installed more than once",
1583 skill.name
1584 ));
1585 }
1586 let validation = skill.validation(require_http_support);
1587 skill_steps += validation.steps;
1588 skill_tools.extend(
1589 skill
1590 .tools
1591 .iter()
1592 .map(|tool| format!("{}__{}", skill.name, tool.tool.name)),
1593 );
1594 errors.extend(
1595 validation
1596 .errors
1597 .into_iter()
1598 .map(|problem| format!("skill '{}': {problem}", skill.name)),
1599 );
1600 warnings.extend(
1601 validation
1602 .warnings
1603 .into_iter()
1604 .filter(|warning| warning != UNPINNED_EXTRACTION_WARNING)
1607 .map(|warning| format!("skill '{}': {warning}", skill.name)),
1608 );
1609 }
1610 } else if !self.task_scenarios.is_empty() {
1611 errors.push("task_scenarios require skills".into());
1612 }
1613
1614 for use_frag in &self.use_fragments {
1616 if use_frag.namespace.is_empty() {
1617 errors.push(
1618 "use_fragments directive has empty namespace — step ids would be malformed"
1619 .into(),
1620 );
1621 }
1622 }
1623
1624 let flow = match self.effective_flow() {
1625 Ok(flow) => flow,
1626 Err(errs) => {
1627 errors.extend(errs);
1628 self.flow.clone().unwrap_or_default()
1629 }
1630 };
1631 for stage in self.conversation_stages() {
1632 for resolve in &stage.resolve {
1633 let name = resolve.resolver.as_deref().unwrap_or(&resolve.slot);
1634 if !self.tools.iter().any(|t| t.name == name) {
1635 errors.push(format!(
1636 "stage '{}' resolves '{}' with '{name}', which is not a declared tool",
1637 stage.id, resolve.slot
1638 ));
1639 }
1640 }
1641 }
1642 if !self.scenarios.is_empty() && self.conversation.is_none() {
1643 errors.push("`scenarios` need a `conversation` to run against".into());
1644 }
1645 let mermaid = flow.to_mermaid();
1646 let steps = flow.steps.len();
1647 let has_flow = !flow.steps.is_empty();
1648
1649 if !has_flow && self.phases.is_empty() && self.skills.is_empty() && !allow_ungoverned {
1650 errors.push("spec has neither a flow nor phases — nothing to run".into());
1651 }
1652 if !self.phases.is_empty() && self.initial_phase.is_none() {
1653 errors.push("phases are declared but initial_phase is not set".into());
1654 }
1655 if let Some(initial) = &self.initial_phase
1656 && !self.phases.iter().any(|p| &p.name == initial)
1657 {
1658 errors.push(format!("initial_phase '{initial}' is not a declared phase"));
1659 }
1660 {
1662 let phase_names: std::collections::BTreeSet<&str> =
1663 self.phases.iter().map(|p| p.name.as_str()).collect();
1664 if phase_names.len() != self.phases.len() {
1665 let mut seen = std::collections::BTreeSet::new();
1666 for p in &self.phases {
1667 if !seen.insert(p.name.as_str()) {
1668 errors.push(format!("phase '{}' is declared more than once", p.name));
1669 }
1670 }
1671 }
1672 }
1673 for pattern in &self.patterns {
1674 match (pattern.sustained_secs, pattern.turns) {
1675 (Some(_), Some(_)) | (None, None) => errors.push(format!(
1676 "pattern '{}' must set exactly one of sustained_secs or turns",
1677 pattern.name
1678 )),
1679 _ => {}
1680 }
1681 if guard_uses_marking(&pattern.when) {
1682 errors.push(format!(
1683 "pattern '{}' uses a called_ok/done atom — pattern guards see state only",
1684 pattern.name
1685 ));
1686 }
1687 }
1688 for p in &self.phases {
1689 for t in &p.transitions {
1690 if guard_uses_marking(&t.when) {
1691 errors.push(format!(
1692 "phase '{}' transition to '{}' uses a called_ok/done atom — phase guards \
1693 see state only (no flow marking); latch a state key instead",
1694 p.name, t.to
1695 ));
1696 }
1697 }
1698 }
1699 for t in &self.tools {
1700 if t.http.is_some() && t.mcp.is_some() {
1701 errors.push(format!(
1702 "tool '{}' has both an http and an mcp binding; keep one",
1703 t.name
1704 ));
1705 }
1706 }
1707 if require_http_support && cfg!(not(feature = "http-tools")) {
1708 for t in &self.tools {
1709 if t.http.is_some() {
1710 errors.push(format!(
1711 "tool '{}' has an http binding but the `http-tools` feature is not \
1712 enabled",
1713 t.name
1714 ));
1715 }
1716 }
1717 }
1718
1719 {
1723 let computed_keys: std::collections::BTreeSet<&str> =
1724 self.computed.iter().map(|c| c.key.as_str()).collect();
1725 if computed_keys.len() != self.computed.len() {
1726 errors.push("computed variables declare a duplicate key".into());
1727 }
1728 let normalize = |k: &str| k.strip_prefix("derived:").unwrap_or(k).to_string();
1729 let mut in_degree: BTreeMap<&str, usize> =
1730 computed_keys.iter().map(|k| (*k, 0)).collect();
1731 let mut dependents: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
1732 for c in &self.computed {
1733 for dep in c.from.keys_read() {
1734 let dep = normalize(&dep);
1735 if dep != c.key
1736 && let Some(&dep_key) = computed_keys.get(dep.as_str())
1737 {
1738 dependents.entry(dep_key).or_default().push(c.key.as_str());
1739 *in_degree.entry(c.key.as_str()).or_default() += 1;
1740 }
1741 if dep == c.key {
1742 errors.push(format!("computed '{}' reads its own key", c.key));
1743 }
1744 }
1745 }
1746 let mut queue: Vec<&str> = in_degree
1747 .iter()
1748 .filter(|(_, d)| **d == 0)
1749 .map(|(k, _)| *k)
1750 .collect();
1751 let mut visited = 0usize;
1752 while let Some(key) = queue.pop() {
1753 visited += 1;
1754 for dependent in dependents.get(key).cloned().unwrap_or_default() {
1755 let Some(d) = in_degree.get_mut(dependent) else {
1759 continue;
1760 };
1761 *d -= 1;
1762 if *d == 0 {
1763 queue.push(dependent);
1764 }
1765 }
1766 }
1767 if visited != computed_keys.len() {
1768 let cycle: Vec<&str> = in_degree
1769 .iter()
1770 .filter(|(_, d)| **d > 0)
1771 .map(|(k, _)| *k)
1772 .collect();
1773 errors.push(format!(
1774 "computed variables form a dependency cycle: {}",
1775 cycle.join(", ")
1776 ));
1777 }
1778 }
1779
1780 for (location, effect) in self.all_effects() {
1783 if matches!(effect, EffectSpec::Remember(_)) && self.memory.is_none() {
1784 errors.push(format!(
1785 "{location} uses a `remember` effect but the spec has no `memory` section"
1786 ));
1787 }
1788 }
1789 if let Some(memory) = &self.memory {
1790 for slot in &memory.slots {
1791 if slot.to.starts_with("derived:") {
1792 errors.push(format!(
1793 "memory slot '{}' targets read-only key '{}' — the `derived:` scope \
1794 belongs to computed variables",
1795 slot.predicate, slot.to
1796 ));
1797 }
1798 }
1799 }
1800
1801 for (key, field) in &self.state {
1804 if let (Some(kind), Some(default)) = (field.kind, &field.default)
1805 && !kind.matches(default)
1806 {
1807 warnings.push(format!(
1808 "state key '{key}' declares type {kind:?} but its default is {default}"
1809 ));
1810 }
1811 }
1812 if !self.state.is_empty() {
1813 let declared: std::collections::BTreeSet<&str> =
1814 self.state.keys().map(String::as_str).collect();
1815 let mut undeclared = std::collections::BTreeSet::new();
1816 for key in &written {
1817 let bare = key.strip_prefix("derived:").unwrap_or(key);
1818 if !declared.contains(bare) && !self.computed.iter().any(|c| c.key == bare) {
1819 undeclared.insert(key.clone());
1820 }
1821 }
1822 for key in &undeclared {
1823 warnings.push(format!(
1824 "state key '{key}' is written but not declared in the `state` section"
1825 ));
1826 }
1827 }
1828
1829 {
1832 for c in &self.computed {
1833 for dep in c.from.keys_read() {
1834 let bare = dep.strip_prefix("derived:").unwrap_or(&dep);
1835 if !written.contains(&dep)
1836 && !written.contains(bare)
1837 && !dep.ends_with(":result")
1838 {
1839 warnings.push(format!(
1840 "computed '{}' reads state key '{dep}' but nothing writes it",
1841 c.key
1842 ));
1843 }
1844 }
1845 }
1846 }
1847
1848 if let Some(runtime) = &self.runtime {
1850 if runtime.include_thoughts == Some(true) && runtime.thinking_budget.is_none() {
1851 warnings.push(
1852 "runtime.include_thoughts is set without runtime.thinking_budget — no \
1853 thoughts will arrive"
1854 .into(),
1855 );
1856 }
1857 if let Some(audio) = &runtime.audio {
1858 if audio.denoise == Some(true) && !cfg!(feature = "denoise") {
1859 warnings.push(
1860 "runtime.audio.denoise requires building with the `denoise` feature — \
1861 the stage will be skipped"
1862 .into(),
1863 );
1864 }
1865 if audio.authority == Some(AuthoritySpec::Client) && audio.denoise != Some(true) {
1866 warnings.push(
1867 "runtime.audio.authority=client without denoise — in noise the raw \
1868 energy VAD latches open and will drive interruptions falsely \
1869 (measured); enable denoise or expect spurious barge-ins"
1870 .into(),
1871 );
1872 }
1873 if audio.noise_gate.is_some() && audio.denoise != Some(true) {
1874 warnings.push(
1875 "runtime.audio.noise_gate without denoise — the gate calibrates on \
1876 noisy levels; chain it behind denoise so it gates clean audio"
1877 .into(),
1878 );
1879 }
1880 if audio.authority == Some(AuthoritySpec::Client) && runtime.vad.is_some() {
1881 warnings.push(
1882 "runtime.audio.authority=client disables the server's automatic \
1883 activity detection — runtime.vad sensitivities will have no effect"
1884 .into(),
1885 );
1886 }
1887 if let Some(eot_ms) = audio.eot_hold_ms
1888 && eot_ms > 1600
1889 {
1890 warnings.push(
1891 "runtime.audio.eot_hold_ms exceeds the measured frontier (1600 ms): \
1892 recall fell to 0.508 at 1600ms on TurnBench dev — values beyond this \
1893 may cause missed turn-end detection"
1894 .into(),
1895 );
1896 }
1897 if let Some(min_int_ms) = audio.min_interruption_ms
1898 && min_int_ms > 2000
1899 {
1900 warnings.push(
1901 "runtime.audio.min_interruption_ms exceeds the interruption match \
1902 window (2000 ms) — commits may land too late to count"
1903 .into(),
1904 );
1905 }
1906 }
1907 if runtime.session_id.is_some() && runtime.persistence.is_none() {
1908 warnings.push(
1909 "runtime.session_id is set without runtime.persistence — nothing will be \
1910 snapshotted"
1911 .into(),
1912 );
1913 }
1914 }
1915
1916 let (valid_flow, referenced) = if has_flow {
1920 let compile_result = if self.tools.is_empty() || !self.mcp.is_empty() {
1921 if !self.mcp.is_empty() && !self.tools.is_empty() {
1922 warnings.push(
1923 "MCP toolsets resolve at connect time, so tool-name checking against \
1924 the flow is skipped"
1925 .into(),
1926 );
1927 }
1928 flow.clone().compile()
1929 } else {
1930 let mut names = self.tool_names();
1931 if self.memory.is_some() {
1932 names.extend(
1935 MEMORY_TOOL_NAMES
1936 .iter()
1937 .map(std::string::ToString::to_string),
1938 );
1939 }
1940 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1941 flow.clone().compile_with_tools(&refs)
1942 };
1943 match compile_result {
1944 Ok(compiled) => (
1945 true,
1946 compiled
1947 .tool_surface()
1948 .tools
1949 .iter()
1950 .cloned()
1951 .collect::<Vec<_>>(),
1952 ),
1953 Err(errs) => {
1954 errors.extend(errs.0.iter().map(std::string::ToString::to_string));
1955 (false, Vec::new())
1956 }
1957 }
1958 } else {
1959 (true, Vec::new())
1960 };
1961
1962 if valid_flow && has_flow {
1963 for key in flow.state_keys_read() {
1966 if written.contains(&key) || RUNTIME_WRITTEN.iter().any(|p| key.starts_with(p)) {
1967 continue;
1968 }
1969 if key.ends_with(":result") {
1971 continue;
1972 }
1973 let hint = written
1974 .iter()
1975 .filter(|w| gemini_adk_rs::utils::text::levenshtein(&key, w) <= 2)
1976 .cloned()
1977 .collect::<Vec<_>>();
1978 let suffix = if hint.is_empty() {
1979 String::new()
1980 } else {
1981 format!(" — did you mean {}?", hint.join(" / "))
1982 };
1983 warnings.push(format!(
1984 "a guard reads state key '{key}' but no tool, extractor, phase, or watcher \
1985 writes it (it can never latch){suffix}"
1986 ));
1987 }
1988 let overlay_tools: std::collections::BTreeSet<&str> = self
1991 .conversation
1992 .iter()
1993 .flat_map(|c| c.overlays.iter().flat_map(|o| o.stages.iter()))
1994 .flat_map(|s| {
1995 s.allow
1996 .iter()
1997 .map(String::as_str)
1998 .chain(s.commit.iter().map(|c| c.tool.as_str()))
1999 })
2000 .collect();
2001 for t in &self.tools {
2002 if !referenced.contains(&t.name) && !overlay_tools.contains(t.name.as_str()) {
2003 warnings.push(format!(
2004 "tool '{}' is declared but no step or constraint references it \
2005 (it will be denied whenever a step with an `allow` list is active \
2006 unless you add it to `ambient`)",
2007 t.name
2008 ));
2009 }
2010 }
2011 for s in &flow.steps {
2012 if !s.terminal && s.posture.is_none() {
2013 warnings.push(format!(
2014 "step '{}' has no posture — the model gets no steering while it is active",
2015 s.id
2016 ));
2017 }
2018 }
2019 }
2020
2021 if self.uses_default_extraction_model() {
2023 warnings.push(UNPINNED_EXTRACTION_WARNING.into());
2024 }
2025 for (place, name) in self
2026 .extract
2027 .iter()
2028 .filter_map(|e| {
2029 e.model
2030 .as_deref()
2031 .map(|m| (format!("extract '{}'", e.name), m))
2032 })
2033 .chain(
2034 self.models
2035 .extraction
2036 .as_deref()
2037 .map(|m| ("models.extraction".into(), m)),
2038 )
2039 {
2040 if name.trim().is_empty() {
2041 errors.push(format!("{place}: model is empty"));
2042 }
2043 }
2044
2045 let (decision_errors, decision_warnings) = self.decision_problems();
2047 errors.extend(decision_errors);
2048 warnings.extend(decision_warnings);
2049
2050 let (code_errors, code_warnings) = self.code_problems();
2052 errors.extend(code_errors);
2053 warnings.extend(code_warnings);
2054
2055 SpecValidation {
2056 valid: errors.is_empty(),
2057 errors,
2058 warnings,
2059 mermaid,
2060 tools: referenced.into_iter().chain(skill_tools).collect(),
2061 steps: steps + skill_steps,
2062 }
2063 }
2064
2065 pub fn build_dispatcher(&self, state: &State) -> ToolDispatcher {
2067 self.build_dispatcher_with(state, &SpecResources::default())
2068 }
2069
2070 pub fn build_dispatcher_with(
2074 &self,
2075 state: &State,
2076 resources: &SpecResources,
2077 ) -> ToolDispatcher {
2078 let mut dispatcher = ToolDispatcher::new();
2079 for tool in self.bound_tools(state, resources) {
2080 dispatcher.register(tool);
2081 }
2082 dispatcher
2083 }
2084
2085 fn bound_tools(&self, state: &State, resources: &SpecResources) -> Vec<Arc<SimpleTool>> {
2088 let mut servers: BTreeMap<String, Arc<gemini_adk_rs::tools::mcp::McpSessionManager>> =
2089 BTreeMap::new();
2090 let mut tools = Vec::new();
2091 for tool in &self.tools {
2092 let call = match (resources.tools.get(&tool.name), &tool.mcp) {
2093 (Some(implementation), _) => ToolCall::Code(implementation.clone()),
2094 (None, Some(params)) => ToolCall::Mcp(
2095 servers
2096 .entry(params.clone())
2097 .or_insert_with(|| {
2098 Arc::new(gemini_adk_rs::tools::mcp::McpSessionManager::new(
2099 crate::live::connect::parse_mcp_params(params),
2100 ))
2101 })
2102 .clone(),
2103 ),
2104 (None, None) => ToolCall::Declared,
2105 };
2106 tools.push(Arc::new(build_tool(tool, state, call)));
2107 }
2108 tools
2109 }
2110
2111 pub(crate) fn apply_tool_state(&self, name: &str, state: &State) {
2114 if let Some(tool) = self.tools.iter().find(|t| t.name == name) {
2115 for (key, value) in &tool.set_state {
2116 let _ = state.set(key, value.clone());
2117 }
2118 }
2119 }
2120
2121 pub fn run_tests(&self) -> Vec<TestReport> {
2125 let mut reports = simulate::run_tests(self);
2126 for skill in &self.skills {
2127 reports.extend(skill.run_tests().into_iter().map(|mut report| {
2128 report.name = format!("{}/{}", skill.name, report.name);
2129 report
2130 }));
2131 }
2132 reports
2133 }
2134
2135 pub fn sandboxed(&self, allow: &BindingAllowlist) -> (SessionSpec, Vec<String>) {
2144 let mut spec = self.clone();
2145 let mut notes = Vec::new();
2146 for skill in &mut spec.skills {
2147 let (sandboxed, disabled) = skill.sandboxed(allow);
2148 *skill = sandboxed;
2149 notes.extend(disabled);
2150 }
2151 spec.mcp.retain(|params| {
2152 let keep = allow.allows_mcp(params);
2153 if !keep {
2154 notes.push(format!(
2155 "mcp entry `{params}` is not allowed on this server; removed"
2156 ));
2157 }
2158 keep
2159 });
2160 for tool in &mut spec.tools {
2161 if let Some(params) = &tool.mcp
2162 && !allow.allows_mcp(params)
2163 {
2164 notes.push(format!(
2165 "tool `{}`: MCP binding `{params}` is not allowed on this server; it runs as a mock",
2166 tool.name
2167 ));
2168 tool.mcp = None;
2169 }
2170 let Some(binding) = &mut tool.http else {
2171 continue;
2172 };
2173 if allow.allows_http(&binding.url) {
2174 binding.reach = Some(allow.clone());
2177 } else {
2178 notes.push(format!(
2179 "tool `{}`: HTTP binding to `{}` is not allowed on this server; it runs as a mock",
2180 tool.name, binding.url
2181 ));
2182 tool.http = None;
2183 }
2184 }
2185 (spec, notes)
2186 }
2187
2188 pub fn apply(
2199 &self,
2200 live: Live,
2201 state: &State,
2202 resources: &SpecResources,
2203 ) -> Result<Live, String> {
2204 let validation = self.validate();
2205 if !validation.valid {
2206 return Err(format!(
2207 "spec failed validation: {}",
2208 validation.errors.join("; ")
2209 ));
2210 }
2211 if self.requires_extraction()
2212 && self.uses_default_extraction_model()
2213 && resources.extraction_llm.is_none()
2214 {
2215 return Err(
2216 "spec declares extraction that names no model, and SpecResources.extraction_llm \
2217 is not set; set models.extraction"
2218 .into(),
2219 );
2220 }
2221 if self.requires_memory() && resources.memory.is_none() {
2222 return Err("spec declares memory but SpecResources.memory is not set".into());
2223 }
2224 if !self.decisions.is_empty() && resources.decision_model.is_none() {
2225 return Err(
2226 "spec declares decisions but SpecResources.decision_model is not set \
2227 (for Jev on Vercel AI Gateway: GatewayDecisionModel::from_env(), which reads \
2228 AI_GATEWAY_API_KEY)"
2229 .into(),
2230 );
2231 }
2232 if let Some(name) = resources.tools.keys().find(|name| {
2233 !self.tools.iter().any(|t| &&t.name == name)
2234 && !self.skills.iter().any(|skill| {
2235 skill.tools.iter().any(|tool| {
2236 *name == &tool.tool.name
2237 || **name == format!("{}/{}", skill.name, tool.tool.name)
2238 })
2239 })
2240 }) {
2241 return Err(format!(
2242 "SpecResources implements tool '{name}', which the spec does not declare"
2243 ));
2244 }
2245
2246 self.seed_state_defaults(state);
2248
2249 let mut live = live
2250 .state(state.clone())
2251 .instruction(if self.instruction.is_empty() {
2252 "Follow the conversation flow you are given.".to_string()
2253 } else {
2254 self.instruction.clone()
2255 });
2256
2257 if let Some(greeting) = &self.greeting {
2258 live = live.greeting(greeting.clone());
2259 }
2260 live = match self.modality {
2261 SpecModality::Text => live.text_only(),
2262 SpecModality::Audio => live.voice(resolve_voice(self.voice.as_deref())),
2263 };
2264
2265 if !self.skills.is_empty() {
2266 let runtime = self.compile_tasks(resources)?;
2267 live = live.tasks(runtime);
2268 if self.skills.iter().any(|skill| skill.memory.is_some())
2269 && let Some(binding) = &resources.memory
2270 {
2271 live = binding.install_task_lifecycle(live);
2272 }
2273 }
2274
2275 let tools = self.bound_tools(state, resources);
2278 if !tools.is_empty() {
2279 let mut dispatcher = ToolDispatcher::new();
2280 for tool in &tools {
2281 dispatcher.register(tool.clone());
2282 }
2283 live = live.dispatcher(dispatcher);
2284 }
2285 for params in &self.mcp {
2286 live = live.tools(T::mcp(params.clone()));
2287 }
2288
2289 if let Some(conversation) = &self.conversation {
2292 let compiled = crate::conversation::Conversation::from_spec_with_resolvers(
2293 conversation.clone(),
2294 &self.resolver_registry(&tools),
2295 )
2296 .map_err(|e| format!("conversation: {e}"))?;
2297 live = live.converse(&compiled);
2298 } else {
2299 let flow = self.effective_flow().map_err(|e| e.join("; "))?;
2300 if !flow.steps.is_empty() {
2301 live = live.govern(flow);
2302 }
2303 }
2304
2305 for c in &self.computed {
2308 let expr = c.from.clone();
2309 let deps: Vec<String> = expr.keys_read().into_iter().collect();
2310 let dep_refs: Vec<&str> = deps.iter().map(String::as_str).collect();
2311 live = live.computed(c.key.clone(), &dep_refs, move |s| expr.eval(s));
2312 }
2313
2314 let memory_binding = resources.memory.clone();
2316 if let (Some(memory), Some(binding)) = (&self.memory, &memory_binding) {
2317 live = binding.install(live, memory);
2318 }
2319
2320 for tool in &self.tools {
2322 match (tool.background, tool.scheduling) {
2323 (_, Some(scheduling)) => {
2324 live = live
2325 .tool_background_with_scheduling(tool.name.clone(), scheduling.to_wire());
2326 }
2327 (true, None) => {
2328 live = live.tool_background(tool.name.clone());
2329 }
2330 (false, None) => {}
2331 }
2332 }
2333
2334 if let Some(runtime) = &self.runtime {
2336 live = apply_runtime(live, runtime);
2337 }
2338
2339 let mut models = BTreeMap::new();
2341 for e in &self.extract {
2342 let llm =
2343 extraction_llm_for(e, self.models.extraction.as_deref(), resources, &mut models)?;
2344 live = live.extractor(Arc::new(compile_extractor(e, llm, &self.models)));
2345 }
2346 if let Some(model) = &resources.decision_model
2347 && !self.decisions.is_empty()
2348 {
2349 live = live.decisions(self.compile_decisions(model.clone()));
2350 }
2351 if let Some(code) = self.compile_code_mode(resources.code_sandbox.clone()) {
2352 live = live.code_mode(code);
2353 }
2354
2355 for p in &self.phases {
2357 let mut builder = live.phase(p.name.clone());
2358 if let Some(instruction) = &p.instruction {
2359 builder = builder.instruction(instruction.clone());
2360 }
2361 if !p.tools.is_empty() {
2362 builder = builder.tools(p.tools.clone());
2363 }
2364 if !p.needs.is_empty() {
2365 let refs: Vec<&str> = p.needs.iter().map(String::as_str).collect();
2366 builder = builder.needs(&refs);
2367 }
2368 if p.prompt_on_enter == Some(true) {
2369 builder = builder.prompt_on_enter();
2370 }
2371 if p.terminal {
2372 builder = builder.terminal();
2373 }
2374 for t in &p.transitions {
2375 let guard = t.when.clone();
2376 let predicate = move |s: &State| guard.eval_state(s);
2377 builder = match &t.description {
2378 Some(desc) => builder.transition_with(&t.to, predicate, desc.clone()),
2379 None => builder.transition(&t.to, predicate),
2380 };
2381 }
2382 if !p.on_enter.is_empty() {
2383 let effects = p.on_enter.clone();
2384 let memory = memory_binding.clone();
2385 builder = builder.on_enter(move |state, writer| {
2386 let effects = effects.clone();
2387 let memory = memory.clone();
2388 async move {
2389 run_effects(&effects, &state, &writer, memory.as_ref()).await;
2390 }
2391 });
2392 }
2393 live = builder.done();
2394 }
2395 if let Some(initial) = &self.initial_phase {
2396 live = live.initial_phase(initial.clone());
2397 }
2398
2399 for pattern in &self.patterns {
2401 let guard = pattern.when.clone();
2402 let condition = move |s: &State| guard.eval_state(s);
2403 let effects = pattern.effects.clone();
2404 let memory = memory_binding.clone();
2405 let action = move |state: State, writer: Arc<dyn SessionWriter>| {
2406 let effects = effects.clone();
2407 let memory = memory.clone();
2408 async move {
2409 run_effects(&effects, &state, &writer, memory.as_ref()).await;
2410 }
2411 };
2412 if let Some(secs) = pattern.sustained_secs {
2413 live = live.when_sustained(
2414 pattern.name.clone(),
2415 condition,
2416 std::time::Duration::from_secs(secs),
2417 action,
2418 );
2419 } else if let Some(turns) = pattern.turns {
2420 live = live.when_turns(pattern.name.clone(), condition, turns, action);
2421 }
2422 }
2423
2424 for w in &self.watch {
2426 let builder = live.watch(w.key.clone());
2427 let builder = match &w.condition {
2428 WatchCondition::Changed => builder.changed(),
2429 WatchCondition::ChangedTo(v) => builder.changed_to(v.clone()),
2430 WatchCondition::CrossedAbove(t) => builder.crossed_above(*t),
2431 WatchCondition::CrossedBelow(t) => builder.crossed_below(*t),
2432 WatchCondition::BecameTrue => builder.became_true(),
2433 WatchCondition::BecameFalse => builder.became_false(),
2434 };
2435 let sets = w.set.clone();
2436 let effects = w.effects.clone();
2437 let memory = memory_binding.clone();
2438 live = builder.then_with_writer(move |_old, _new, state, writer| {
2439 let sets = sets.clone();
2440 let effects = effects.clone();
2441 let memory = memory.clone();
2442 async move {
2443 for (key, value) in &sets {
2444 let _ = state.set(key, value.clone());
2445 }
2446 run_effects(&effects, &state, &writer, memory.as_ref()).await;
2447 }
2448 });
2449 }
2450
2451 Ok(live)
2452 }
2453}
2454
2455fn compile_extractor(e: &ExtractSpec, llm: Arc<dyn BaseLlm>, models: &ModelsSpec) -> LlmExtractor {
2458 let mut extractor = LlmExtractor::new(e.name.clone(), llm, e.instruction.clone(), e.window)
2459 .with_schema(e.schema.clone())
2460 .with_min_words(3)
2461 .with_trigger(e.trigger.to_trigger());
2462 if let Some(budget) = e.thinking_budget.or(models.extraction_thinking_budget) {
2463 extractor = extractor.with_thinking_budget(Some(budget));
2464 }
2465 if e.promote.is_empty() {
2466 extractor
2467 } else {
2468 extractor.with_promotions(e.promote.iter().map(PromoteSpec::to_rule).collect())
2469 }
2470}
2471
2472async fn run_effects(
2476 effects: &[EffectSpec],
2477 state: &State,
2478 writer: &Arc<dyn SessionWriter>,
2479 memory: Option<&Arc<dyn MemoryBinding>>,
2480) {
2481 for effect in effects {
2482 match effect {
2483 EffectSpec::Set(map) => {
2484 for (key, value) in map {
2485 let _ = state.set(key, value.clone());
2486 }
2487 }
2488 EffectSpec::Context(text) => {
2489 let _ = writer
2490 .send_client_content(vec![Content::model(text.clone())], false)
2491 .await;
2492 }
2493 EffectSpec::Prompt(text) => {
2494 let _ = writer
2495 .send_client_content(vec![Content::model(text.clone())], true)
2496 .await;
2497 }
2498 EffectSpec::Remember(template) => {
2499 if let Some(binding) = memory {
2500 binding.remember(interpolate(template, &Value::Null, state));
2501 }
2502 }
2503 }
2504 }
2505}
2506
2507fn apply_turn_commit(
2511 mut live: Live,
2512 eot_hold_ms: Option<u32>,
2513 min_interruption_ms: Option<u32>,
2514) -> Live {
2515 if let Some(ms) = eot_hold_ms {
2516 live = live.turn_commit_eot_hold_ms(u64::from(ms));
2517 }
2518 if let Some(ms) = min_interruption_ms {
2519 live = live.turn_commit_min_interruption_ms(u64::from(ms));
2520 }
2521 live
2522}
2523
2524fn apply_runtime(mut live: Live, runtime: &RuntimeSpec) -> Live {
2526 if let Some(t) = runtime.temperature {
2527 live = live.temperature(t);
2528 }
2529 if let Some(budget) = runtime.thinking_budget {
2530 live = live.thinking(budget);
2531 }
2532 if runtime.include_thoughts == Some(true) {
2533 live = live.include_thoughts();
2534 }
2535 if let Some(t) = runtime.transcription {
2536 if t.input {
2537 live = live.input_transcription();
2538 }
2539 if t.output {
2540 live = live.output_transcription();
2541 }
2542 }
2543 if runtime.proactive_audio == Some(true) {
2544 live = live.proactive_audio();
2545 }
2546 if let Some(vad) = &runtime.vad {
2547 live = live.vad(AutomaticActivityDetection {
2548 disabled: None,
2549 start_of_speech_sensitivity: vad.start_sensitivity.map(SensitivitySpec::to_wire),
2550 end_of_speech_sensitivity: vad.end_sensitivity.map(SensitivitySpec::to_wire),
2551 prefix_padding_ms: vad.prefix_padding_ms,
2552 silence_duration_ms: vad.silence_duration_ms,
2553 });
2554 }
2555 if let Some(audio) = &runtime.audio {
2556 #[cfg(feature = "denoise")]
2557 if audio.denoise == Some(true) {
2558 live = live.mic_denoise();
2559 }
2560 if let Some(gate) = &audio.noise_gate {
2561 live = live.mic_noise_gate(gate.threshold_rms, gate.hold_frames);
2562 }
2563 if let Some(vad) = &audio.client_vad {
2564 live = live.input_vad(vad.to_config());
2565 }
2566 if audio.authority == Some(AuthoritySpec::Client) {
2567 live = live.client_interruption_authority();
2568 }
2569 live = apply_turn_commit(live, audio.eot_hold_ms, audio.min_interruption_ms);
2572 }
2573 if let Some(ms) = runtime.soft_turn_timeout_ms {
2574 live = live.soft_turn_timeout(std::time::Duration::from_millis(ms));
2575 }
2576 if let Some(steering) = runtime.steering {
2577 live = live.steering_mode(match steering {
2578 SteeringSpec::InstructionUpdate => SteeringMode::InstructionUpdate,
2579 SteeringSpec::ContextInjection => SteeringMode::ContextInjection,
2580 SteeringSpec::Hybrid => SteeringMode::Hybrid,
2581 SteeringSpec::ContextUpdate => SteeringMode::ContextUpdate,
2582 });
2583 }
2584 if let Some(delivery) = runtime.context_delivery {
2585 live = live.context_delivery(match delivery {
2586 ContextDeliverySpec::Immediate => ContextDelivery::Immediate,
2587 ContextDeliverySpec::Deferred => ContextDelivery::Deferred,
2588 });
2589 }
2590 if let Some(repair) = runtime.repair {
2591 live = live.repair(RepairConfig {
2592 nudge_after: repair.nudge_after,
2593 escalate_after: repair.escalate_after,
2594 });
2595 }
2596 if let Some(persistence) = &runtime.persistence {
2597 live = match persistence {
2598 PersistenceSpec::Fs { dir } => {
2599 live.persistence(Arc::new(gemini_adk_rs::live::FsPersistence::new(dir)))
2600 }
2601 PersistenceSpec::Memory => {
2602 live.persistence(Arc::new(gemini_adk_rs::live::MemoryPersistence::new()))
2603 }
2604 };
2605 }
2606 if let Some(id) = &runtime.session_id {
2607 live = live.session_id(id.clone());
2608 }
2609 if runtime.lossy_audio {
2610 live = live.lossy_audio();
2611 }
2612 if runtime.lossy_transcript {
2613 live = live.lossy_transcript();
2614 }
2615 live
2616}
2617
2618enum ToolCall {
2620 Declared,
2622 Code(Arc<dyn ToolFunction>),
2624 Mcp(Arc<gemini_adk_rs::tools::mcp::McpSessionManager>),
2626}
2627
2628fn mcp_value(result: Value) -> Value {
2631 if let Some(structured) = result.get("structuredContent") {
2632 return structured.clone();
2633 }
2634 let texts: Vec<&str> = result["content"]
2635 .as_array()
2636 .into_iter()
2637 .flatten()
2638 .filter_map(|part| part["text"].as_str())
2639 .collect();
2640 match texts.as_slice() {
2641 [text] => serde_json::from_str(text).unwrap_or_else(|_| json!({ "output": text })),
2642 [] => result,
2643 many => json!({ "output": many.join("\n") }),
2644 }
2645}
2646
2647fn build_tool(tool: &ToolSpec, state: &State, call: ToolCall) -> SimpleTool {
2650 let description = if tool.description.is_empty() {
2651 format!("Tool '{}'", tool.name)
2652 } else {
2653 tool.description.clone()
2654 };
2655 let response = tool.response.clone().unwrap_or_else(|| json!({"ok": true}));
2656 let sets = tool.set_state.clone();
2657 let save_as = tool.save_response_as.clone();
2658 let http = tool.http.clone();
2659 let st = state.clone();
2660 let name = tool.name.clone();
2661 let call = Arc::new(call);
2662 SimpleTool::new(
2663 &tool.name,
2664 description,
2665 tool.parameters.clone(),
2666 move |args| {
2667 let response = response.clone();
2668 let sets = sets.clone();
2669 let save_as = save_as.clone();
2670 let http = http.clone();
2671 let st = st.clone();
2672 let name = name.clone();
2673 let call = call.clone();
2674 async move {
2675 let result = match (call.as_ref(), &http) {
2676 (ToolCall::Code(implementation), _) => implementation.call(args).await?,
2677 (ToolCall::Mcp(server), _) => {
2678 mcp_value(server.call_tool(&name, args).await.map_err(|e| {
2679 gemini_adk_rs::error::ToolError::ExecutionFailed(format!("{name}: {e}"))
2680 })?)
2681 }
2682 (ToolCall::Declared, Some(binding)) => {
2683 execute_http(binding, &args, &st).await.map_err(|e| {
2684 gemini_adk_rs::error::ToolError::Other(format!("{name}: {e}"))
2685 })?
2686 }
2687 (ToolCall::Declared, None) => response,
2688 };
2689 for (key, value) in &sets {
2690 let _ = st.set(key, value.clone());
2691 }
2692 if let Some(key) = &save_as {
2693 let _ = st.set(key, result.clone());
2694 }
2695 Ok(result)
2696 }
2697 },
2698 )
2699}
2700
2701fn interpolate(template: &str, args: &Value, state: &State) -> String {
2703 gemini_adk_rs::utils::text::interpolate_with(template, |expr| {
2704 if let Some(field) = expr.strip_prefix("args.") {
2705 args.get(field).cloned()
2706 } else if let Some(key) = expr.strip_prefix("state.") {
2707 state.get::<Value>(key)
2708 } else {
2709 None
2710 }
2711 })
2712}
2713
2714#[cfg_attr(not(feature = "http-tools"), allow(dead_code))]
2716fn interpolate_value(value: &Value, args: &Value, state: &State) -> Value {
2717 match value {
2718 Value::String(s) => Value::String(interpolate(s, args, state)),
2719 Value::Array(items) => Value::Array(
2720 items
2721 .iter()
2722 .map(|v| interpolate_value(v, args, state))
2723 .collect(),
2724 ),
2725 Value::Object(map) => Value::Object(
2726 map.iter()
2727 .map(|(k, v)| (k.clone(), interpolate_value(v, args, state)))
2728 .collect(),
2729 ),
2730 other => other.clone(),
2731 }
2732}
2733
2734#[cfg(feature = "http-tools")]
2735async fn execute_http(binding: &HttpBinding, args: &Value, state: &State) -> Result<Value, String> {
2736 let url = interpolate(&binding.url, args, state);
2737 let mut client = reqwest::Client::builder();
2738 if let Some(reach) = binding.reach.clone() {
2739 if !reach.allows_http(&url) {
2740 return Err(format!("{url} is outside this server's HTTP allowlist"));
2741 }
2742 client = client.redirect(reqwest::redirect::Policy::custom(move |attempt| {
2743 if attempt.previous().len() >= 10 {
2744 attempt.error("too many redirects")
2745 } else if reach.allows_http(attempt.url().as_str()) {
2746 attempt.follow()
2747 } else {
2748 let error = format!(
2749 "redirect to {} is outside this server's HTTP allowlist",
2750 attempt.url()
2751 );
2752 attempt.error(error)
2753 }
2754 }));
2755 }
2756 let client = client.build().map_err(|e| e.to_string())?;
2757 let method = reqwest::Method::from_bytes(binding.method.to_uppercase().as_bytes())
2758 .map_err(|_| format!("invalid HTTP method '{}'", binding.method))?;
2759 let mut request = client.request(method, &url);
2760 for (name, value) in &binding.headers {
2761 request = request.header(name, interpolate(value, args, state));
2762 }
2763 if let Some(body) = &binding.body {
2764 request = request.json(&interpolate_value(body, args, state));
2765 }
2766 let response = request.send().await.map_err(|e| e.to_string())?;
2767 let status = response.status().as_u16();
2768 let text = response.text().await.map_err(|e| e.to_string())?;
2769 Ok(serde_json::from_str(&text).unwrap_or_else(|_| json!({ "status": status, "body": text })))
2770}
2771
2772#[cfg(not(feature = "http-tools"))]
2773#[allow(
2774 clippy::unused_async,
2775 reason = "same signature as the http-tools implementation so the call site is feature-agnostic"
2776)]
2777async fn execute_http(
2778 _binding: &HttpBinding,
2779 _args: &Value,
2780 _state: &State,
2781) -> Result<Value, String> {
2782 Err("http tool bindings require the `http-tools` feature".to_string())
2783}
2784
2785fn splice_fragment(
2787 flow: &mut Flow,
2788 fragment: &Flow,
2789 directive: &UseFragment,
2790 errors: &mut Vec<String>,
2791) {
2792 let ns = &directive.namespace;
2793 let prefix = |id: &str| format!("{ns}/{id}");
2794 let internal: std::collections::BTreeSet<&str> =
2795 fragment.steps.iter().map(|s| s.id.as_str()).collect();
2796
2797 for step in &fragment.steps {
2798 let new_id = prefix(&step.id);
2799 if flow.steps.iter().any(|s| s.id == new_id) {
2800 errors.push(format!(
2801 "fragment splice '{ns}' collides with existing step '{new_id}'"
2802 ));
2803 continue;
2804 }
2805 let mut after: Vec<gemini_adk_rs::flow::Edge> = step
2806 .after
2807 .iter()
2808 .map(|d| gemini_adk_rs::flow::Edge {
2809 step: if internal.contains(d.step.as_str()) {
2810 prefix(&d.step)
2811 } else {
2812 d.step.clone()
2813 },
2814 when: d
2815 .when
2816 .clone()
2817 .map(|g| rewrite_guard_steps(g, &internal, ns)),
2818 })
2819 .collect();
2820 if step.after.is_empty() {
2821 after.extend(
2822 directive
2823 .after
2824 .iter()
2825 .cloned()
2826 .map(gemini_adk_rs::flow::Edge::to),
2827 );
2828 }
2829 flow.steps.push(Step {
2830 id: new_id,
2831 after,
2832 join: step.join,
2833 gate: step
2834 .gate
2835 .clone()
2836 .map(|g| rewrite_guard_steps(g, &internal, ns)),
2837 done: step
2838 .done
2839 .clone()
2840 .map(|g| rewrite_guard_steps(g, &internal, ns)),
2841 posture: step.posture.clone(),
2842 ground: step.ground.clone(),
2843 allow: step.allow.clone(),
2844 deny: step.deny.clone(),
2845 terminal: step.terminal,
2846 });
2847 }
2848 for constraint in &fragment.constraints {
2849 flow.constraints.push(match constraint {
2850 Constraint::Once(t) => Constraint::Once(t.clone()),
2851 Constraint::Before(a, b) => Constraint::Before(
2852 if internal.contains(a.as_str()) {
2853 prefix(a)
2854 } else {
2855 a.clone()
2856 },
2857 if internal.contains(b.as_str()) {
2858 prefix(b)
2859 } else {
2860 b.clone()
2861 },
2862 ),
2863 Constraint::NeverUntil { tool, until } => Constraint::NeverUntil {
2864 tool: tool.clone(),
2865 until: rewrite_guard_steps(until.clone(), &internal, ns),
2866 },
2867 Constraint::Require(rs) => Constraint::Require(
2868 rs.iter()
2869 .map(|r| {
2870 if internal.contains(r.as_str()) {
2871 prefix(r)
2872 } else {
2873 r.clone()
2874 }
2875 })
2876 .collect(),
2877 ),
2878 Constraint::Reset { steps, when } => Constraint::Reset {
2879 steps: steps
2880 .iter()
2881 .map(|r| {
2882 if internal.contains(r.as_str()) {
2883 prefix(r)
2884 } else {
2885 r.clone()
2886 }
2887 })
2888 .collect(),
2889 when: rewrite_guard_steps(when.clone(), &internal, ns),
2890 },
2891 });
2892 }
2893 for tool in &fragment.ambient {
2894 if !flow.ambient.contains(tool) {
2895 flow.ambient.push(tool.clone());
2896 }
2897 }
2898 for tool in &fragment.confirm_tools {
2899 if !flow.confirm_tools.contains(tool) {
2900 flow.confirm_tools.push(tool.clone());
2901 }
2902 }
2903}
2904
2905fn rewrite_guard_steps(
2907 guard: Guard,
2908 internal: &std::collections::BTreeSet<&str>,
2909 ns: &str,
2910) -> Guard {
2911 fn rewrite(pred: Pred, internal: &std::collections::BTreeSet<&str>, ns: &str) -> Pred {
2912 match pred {
2913 Pred::Done(s) if internal.contains(s.as_str()) => Pred::Done(format!("{ns}/{s}")),
2914 Pred::All(ps) => Pred::All(ps.into_iter().map(|p| rewrite(p, internal, ns)).collect()),
2915 Pred::Any(ps) => Pred::Any(ps.into_iter().map(|p| rewrite(p, internal, ns)).collect()),
2916 Pred::Not(p) => Pred::Not(Box::new(rewrite(*p, internal, ns))),
2917 other => other,
2918 }
2919 }
2920 match guard {
2921 Guard::Spec(p) => Guard::Spec(rewrite(p, internal, ns)),
2922 custom => custom,
2923 }
2924}
2925
2926fn guard_uses_marking(guard: &Guard) -> bool {
2929 fn walk(pred: &Pred) -> bool {
2930 match pred {
2931 Pred::CalledOk(_) | Pred::Done(_) => true,
2932 Pred::All(ps) | Pred::Any(ps) => ps.iter().any(walk),
2933 Pred::Not(p) => walk(p),
2934 _ => false,
2935 }
2936 }
2937 match guard {
2938 Guard::Spec(p) => walk(p),
2939 Guard::Custom(_) => false,
2940 }
2941}
2942
2943pub fn resolve_voice(name: Option<&str>) -> Voice {
2946 match name {
2947 Some("Aoede") => Voice::Aoede,
2948 Some("Charon") => Voice::Charon,
2949 Some("Fenrir") => Voice::Fenrir,
2950 Some("Kore") => Voice::Kore,
2951 Some("Puck") | None => Voice::Puck,
2952 Some(other) => Voice::Custom(other.to_string()),
2953 }
2954}
2955
2956#[cfg(test)]
2957mod tests {
2958
2959 #[test]
2960 fn audio_spec_lowers_and_validates() {
2961 let spec: SessionSpec = serde_json::from_str(
2962 r#"{
2963 "name": "noisy",
2964 "instruction": "hi",
2965 "runtime": {
2966 "audio": {
2967 "denoise": true,
2968 "noise_gate": { "threshold_rms": 700.0 },
2969 "client_vad": { "preset": "noisy_street", "hangover_frames": 12 },
2970 "authority": "client"
2971 }
2972 }
2973 }"#,
2974 )
2975 .unwrap();
2976 let audio = spec.runtime.as_ref().unwrap().audio.as_ref().unwrap();
2977 assert_eq!(audio.noise_gate.as_ref().unwrap().hold_frames, 3); let config = audio.client_vad.as_ref().unwrap().to_config();
2979 assert_eq!(config.start_threshold_db, 21.0); assert_eq!(config.hangover_frames, 12); assert_eq!(audio.authority, Some(AuthoritySpec::Client));
2982 let json = serde_json::to_value(&spec).unwrap();
2984 let back: SessionSpec = serde_json::from_value(json).unwrap();
2985 assert_eq!(
2986 back.runtime
2987 .unwrap()
2988 .audio
2989 .unwrap()
2990 .client_vad
2991 .unwrap()
2992 .hangover_frames,
2993 Some(12)
2994 );
2995 }
2996
2997 #[test]
2998 fn audio_spec_warns_on_risky_combinations() {
2999 let spec: SessionSpec = serde_json::from_str(
3000 r#"{
3001 "name": "risky",
3002 "instruction": "hi",
3003 "runtime": { "audio": { "authority": "client", "noise_gate": {} } }
3004 }"#,
3005 )
3006 .unwrap();
3007 let validation = spec.validate();
3008 assert!(
3009 validation
3010 .warnings
3011 .iter()
3012 .any(|w| w.contains("authority=client without denoise")),
3013 "expected client-authority warning, got {:?}",
3014 validation.warnings
3015 );
3016 assert!(
3017 validation
3018 .warnings
3019 .iter()
3020 .any(|w| w.contains("noise_gate without denoise")),
3021 "expected gate warning, got {:?}",
3022 validation.warnings
3023 );
3024 }
3025
3026 #[test]
3027 fn turn_commit_tuning_knobs_serialize_and_round_trip() {
3028 let spec: SessionSpec = serde_json::from_str(
3029 r#"{
3030 "name": "tune",
3031 "instruction": "hi",
3032 "runtime": {
3033 "audio": {
3034 "eot_hold_ms": 800,
3035 "min_interruption_ms": 1400
3036 }
3037 }
3038 }"#,
3039 )
3040 .unwrap();
3041 let audio = spec.runtime.as_ref().unwrap().audio.as_ref().unwrap();
3042 assert_eq!(audio.eot_hold_ms, Some(800));
3043 assert_eq!(audio.min_interruption_ms, Some(1400));
3044 let json = serde_json::to_value(&spec).unwrap();
3046 let back: SessionSpec = serde_json::from_value(json).unwrap();
3047 let audio_back = back.runtime.unwrap().audio.unwrap();
3048 assert_eq!(audio_back.eot_hold_ms, Some(800));
3049 assert_eq!(audio_back.min_interruption_ms, Some(1400));
3050 }
3051
3052 #[test]
3053 fn turn_commit_tuning_knobs_validate_thresholds() {
3054 let spec: SessionSpec = serde_json::from_str(
3056 r#"{
3057 "name": "frontier",
3058 "instruction": "hi",
3059 "runtime": { "audio": { "eot_hold_ms": 1700 } }
3060 }"#,
3061 )
3062 .unwrap();
3063 let validation = spec.validate();
3064 assert!(
3065 validation
3066 .warnings
3067 .iter()
3068 .any(|w| w.contains("eot_hold_ms") && w.contains("1600") && w.contains("frontier")),
3069 "expected eot_hold_ms frontier warning, got {:?}",
3070 validation.warnings
3071 );
3072
3073 let spec2: SessionSpec = serde_json::from_str(
3075 r#"{
3076 "name": "window",
3077 "instruction": "hi",
3078 "runtime": { "audio": { "min_interruption_ms": 2100 } }
3079 }"#,
3080 )
3081 .unwrap();
3082 let validation2 = spec2.validate();
3083 assert!(
3084 validation2
3085 .warnings
3086 .iter()
3087 .any(|w| w.contains("min_interruption_ms")
3088 && w.contains("2000")
3089 && w.contains("window")),
3090 "expected min_interruption_ms window warning, got {:?}",
3091 validation2.warnings
3092 );
3093 }
3094 use super::*;
3095
3096 fn collections_spec() -> SessionSpec {
3097 SessionSpec::from_value(json!({
3098 "name": "collections",
3099 "instruction": "Collect payments.",
3100 "tools": [
3101 {"name": "verify_identity", "set_state": {"identity_verified": true}},
3102 {"name": "charge_card", "response": {"charged": true}}
3103 ],
3104 "extract": [{
3105 "name": "ptp",
3106 "instruction": "Extract the promise to pay.",
3107 "schema": {"type": "object", "properties": {
3108 "ptp_amount": {"type": "number"}, "ptp_date": {"type": "string"}}},
3109 "promote": [
3110 {"field": "ptp_amount"},
3111 {"field": "ptp_date", "policy": "overwrite"}
3112 ]
3113 }],
3114 "flow": {
3115 "steps": [
3116 {"id": "verify", "posture": "Verify the caller.",
3117 "allow": ["verify_identity"],
3118 "done": {"is_true": "identity_verified"}},
3119 {"id": "pay", "after": ["verify"], "posture": "Take payment.",
3120 "allow": ["charge_card"],
3121 "gate": {"captured": ["ptp_amount", "ptp_date"]},
3122 "done": {"called_ok": "charge_card"}}
3123 ]
3124 }
3125 }))
3126 .expect("spec parses")
3127 }
3128
3129 #[test]
3130 fn extraction_promotions_satisfy_guard_reads() {
3131 let v = collections_spec().validate();
3132 assert!(v.valid, "errors: {:?}", v.errors);
3133 assert!(
3134 v.warnings.iter().all(|w| !w.contains("can never latch")),
3135 "promoted keys cover the guard reads: {:?}",
3136 v.warnings
3137 );
3138 }
3139
3140 #[test]
3141 fn unwritten_guard_key_warns_with_suggestion() {
3142 let mut spec = collections_spec();
3143 spec.flow.as_mut().unwrap().steps[0].done = Some(Guard::is_true("identity_verifed"));
3145 let v = spec.validate();
3146 assert!(v.valid);
3147 let warning = v
3148 .warnings
3149 .iter()
3150 .find(|w| w.contains("identity_verifed"))
3151 .expect("warns about the unwritten key");
3152 assert!(
3153 warning.contains("identity_verified"),
3154 "suggests the fix: {warning}"
3155 );
3156 }
3157
3158 #[test]
3159 fn phase_guard_rejects_marking_atoms() {
3160 let spec = SessionSpec::from_value(json!({
3161 "instruction": "x",
3162 "phases": [{"name": "a", "transitions": [
3163 {"to": "b", "when": {"called_ok": "some_tool"}}]},
3164 {"name": "b"}],
3165 "initial_phase": "a"
3166 }))
3167 .expect("parses");
3168 let v = spec.validate();
3169 assert!(!v.valid);
3170 assert!(v.errors.iter().any(|e| e.contains("called_ok")));
3171 }
3172
3173 #[test]
3174 fn fragments_splice_with_namespacing() {
3175 let spec = SessionSpec::from_value(json!({
3176 "instruction": "x",
3177 "tools": [
3178 {"name": "check_id", "set_state": {"id_ok": true}},
3179 {"name": "book", "response": {}}
3180 ],
3181 "fragments": {
3182 "verify": {"steps": [
3183 {"id": "ask", "posture": "Ask for ID.", "allow": ["check_id"],
3184 "done": {"is_true": "id_ok"}},
3185 {"id": "confirm", "after": ["ask"], "terminal": true,
3186 "gate": {"done": "ask"}}
3187 ]}
3188 },
3189 "use_fragments": [{"fragment": "verify", "namespace": "v"}],
3190 "flow": {"steps": [
3191 {"id": "book_step", "after": ["v/confirm"], "allow": ["book"],
3192 "done": {"called_ok": "book"}}
3193 ]}
3194 }))
3195 .expect("parses");
3196 let flow = spec.effective_flow().expect("splices");
3197 let ids: Vec<&str> = flow.steps.iter().map(|s| s.id.as_str()).collect();
3198 assert!(ids.contains(&"v/ask") && ids.contains(&"v/confirm"));
3199 let confirm = flow.steps.iter().find(|s| s.id == "v/confirm").unwrap();
3201 assert_eq!(
3202 serde_json::to_value(confirm.gate.as_ref().unwrap()).unwrap(),
3203 json!({"done": "v/ask"})
3204 );
3205 let v = spec.validate();
3206 assert!(v.valid, "errors: {:?}", v.errors);
3207 }
3208
3209 #[test]
3210 fn bare_flow_round_trips() {
3211 let spec = SessionSpec::from_value(json!({
3212 "steps": [{"id": "only", "terminal": true}]
3213 }))
3214 .expect("parses");
3215 assert!(spec.validate().valid);
3216 }
3217
3218 #[test]
3219 fn empty_fragment_namespace_is_rejected() {
3220 let spec = SessionSpec::from_value(json!({
3221 "instruction": "x",
3222 "fragments": {
3223 "verify": {"steps": [
3224 {"id": "ask", "terminal": true}
3225 ]}
3226 },
3227 "use_fragments": [{"fragment": "verify", "namespace": ""}],
3228 "flow": {"steps": [
3229 {"id": "start", "terminal": true}
3230 ]}
3231 }))
3232 .expect("parses");
3233 let v = spec.validate();
3234 assert!(
3236 !v.valid,
3237 "empty namespace should fail validation, got errors: {:?}",
3238 v.errors
3239 );
3240 assert!(
3241 v.errors.iter().any(|e| e.contains("namespace")),
3242 "should mention namespace issue: {:?}",
3243 v.errors
3244 );
3245 }
3246
3247 #[test]
3248 fn duplicate_computed_keys_are_rejected() {
3249 let spec = SessionSpec::from_value(json!({
3250 "instruction": "x",
3251 "flow": {"steps": [{"id": "only", "terminal": true}]},
3252 "computed": [
3253 {"key": "risk", "from": {"key": "score"}},
3254 {"key": "risk", "from": {"key": "other_score"}}
3255 ]
3256 }))
3257 .expect("parses");
3258 let v = spec.validate();
3259 assert!(!v.valid, "duplicate computed keys should fail validation");
3260 assert!(
3261 v.errors.iter().any(|e| e.contains("duplicate")),
3262 "should mention duplicate computed key: {:?}",
3263 v.errors
3264 );
3265 }
3266
3267 #[test]
3268 fn duplicate_phase_names_are_rejected() {
3269 let spec = SessionSpec::from_value(json!({
3270 "instruction": "x",
3271 "phases": [
3272 {"name": "greet", "instruction": "Welcome."},
3273 {"name": "greet", "instruction": "Hi again."}
3274 ],
3275 "initial_phase": "greet"
3276 }))
3277 .expect("parses");
3278 let v = spec.validate();
3279 assert!(!v.valid, "duplicate phase names should fail validation");
3280 assert!(
3281 v.errors.iter().any(|e| e.contains("phase")),
3282 "should mention duplicate phase: {:?}",
3283 v.errors
3284 );
3285 }
3286
3287 #[test]
3288 fn tool_background_false_round_trips() {
3289 let spec = SessionSpec::from_value(json!({
3291 "instruction": "x",
3292 "tools": [
3293 {"name": "search", "background": false},
3294 {"name": "log", "background": true}
3295 ],
3296 "flow": {"steps": [{"id": "only", "terminal": true}]}
3297 }))
3298 .expect("parses");
3299
3300 let serialized = serde_json::to_value(&spec).unwrap();
3302 let tools = serialized["tools"].as_array().unwrap();
3303
3304 assert!(
3307 tools[0].get("background").is_none(),
3308 "background: false is optimized away"
3309 );
3310
3311 assert_eq!(tools[1].get("background"), Some(&json!(true)));
3313
3314 let back: SessionSpec = serde_json::from_value(serialized).unwrap();
3316 assert!(!back.tools[0].background);
3317 assert!(back.tools[1].background);
3318 }
3319
3320 #[test]
3321 fn promotion_spec_with_no_to_field_uses_field_name() {
3322 let spec = SessionSpec::from_value(json!({
3324 "instruction": "x",
3325 "tools": [{"name": "extract", "set_state": {"test": true}}],
3326 "extract": [{
3327 "name": "data",
3328 "instruction": "Extract.",
3329 "schema": {"type": "object"},
3330 "promote": [
3331 {"field": "amount"},
3332 {"field": "date", "to": "extracted_date"}
3333 ]
3334 }],
3335 "flow": {"steps": [{"id": "only", "terminal": true}]}
3336 }))
3337 .expect("parses");
3338
3339 let promote = &spec.extract[0].promote;
3340 assert_eq!(promote[0].target(), "amount");
3341 assert_eq!(promote[1].target(), "extracted_date");
3342 }
3343
3344 #[test]
3345 fn spec_schema_publishes() {
3346 let schema = SessionSpec::json_schema().to_string();
3347 for token in [
3348 "is_true",
3349 "never_until",
3350 "set_state",
3351 "use_fragments",
3352 "promote",
3353 ] {
3354 assert!(schema.contains(token), "schema missing {token}");
3355 }
3356 }
3357
3358 #[test]
3359 fn interpolation_reads_args_and_state() {
3360 let state = State::new();
3361 let _ = state.set("city", "Paris");
3362 let args = json!({"guests": 4});
3363 assert_eq!(
3364 interpolate("book/{state.city}/{args.guests}/{missing}", &args, &state),
3365 "book/Paris/4/"
3366 );
3367 }
3368
3369 #[test]
3370 fn resolve_known_voices() {
3371 assert!(matches!(resolve_voice(Some("Aoede")), Voice::Aoede));
3372 assert!(matches!(resolve_voice(Some("Charon")), Voice::Charon));
3373 assert!(matches!(resolve_voice(Some("Fenrir")), Voice::Fenrir));
3374 assert!(matches!(resolve_voice(Some("Kore")), Voice::Kore));
3375 assert!(matches!(resolve_voice(Some("Puck")), Voice::Puck));
3376 assert!(matches!(resolve_voice(None), Voice::Puck));
3377 }
3378
3379 #[test]
3380 fn resolve_custom_voice() {
3381 assert_eq!(
3382 resolve_voice(Some("CustomVoice")),
3383 Voice::Custom("CustomVoice".into())
3384 );
3385 }
3386
3387 #[test]
3389 fn did_you_mean_distance_counts_characters() {
3390 use gemini_adk_rs::utils::text::levenshtein;
3391 assert_eq!(levenshtein("caller_name", "caller_nane"), 1);
3392 assert_eq!(levenshtein("café", "cafe"), 1);
3393 }
3394
3395 #[tokio::test]
3396 async fn declared_tools_write_state() {
3397 let spec = collections_spec();
3398 let state = State::new();
3399 let dispatcher = spec.build_dispatcher(&state);
3400 let out = dispatcher
3401 .call_function("verify_identity", json!({}))
3402 .await
3403 .expect("tool runs");
3404 assert_eq!(out, json!({"ok": true}));
3405 assert_eq!(state.get::<bool>("identity_verified"), Some(true));
3406 }
3407
3408 #[test]
3409 fn computed_cycles_are_load_time_errors() {
3410 let spec = SessionSpec::from_value(json!({
3411 "instruction": "x",
3412 "flow": {"steps": [{"id": "only", "terminal": true}]},
3413 "computed": [
3414 {"key": "a", "from": {"add": [{"key": "b"}, {"const": 1}]}},
3415 {"key": "b", "from": {"add": [{"key": "derived:a"}, {"const": 1}]}}
3416 ]
3417 }))
3418 .expect("parses");
3419 let v = spec.validate();
3420 assert!(!v.valid);
3421 assert!(v.errors.iter().any(|e| e.contains("dependency cycle")));
3422
3423 let self_read = SessionSpec::from_value(json!({
3424 "instruction": "x",
3425 "flow": {"steps": [{"id": "only", "terminal": true}]},
3426 "computed": [{"key": "a", "from": {"key": "a"}}]
3427 }))
3428 .expect("parses");
3429 assert!(
3430 self_read
3431 .validate()
3432 .errors
3433 .iter()
3434 .any(|e| e.contains("reads its own key"))
3435 );
3436 }
3437
3438 #[test]
3439 fn computed_keys_satisfy_guard_reads_and_deps_are_checked() {
3440 let spec = SessionSpec::from_value(json!({
3441 "instruction": "x",
3442 "tools": [{"name": "record", "set_state": {"score": 0.8}}],
3443 "computed": [{"key": "high_risk",
3444 "from": {"gt": [{"key": "score"}, {"const": 0.5}]}}],
3445 "flow": {"steps": [
3446 {"id": "assess", "posture": "Assess.", "allow": ["record"],
3447 "done": {"is_true": "high_risk"}}
3448 ]}
3449 }))
3450 .expect("parses");
3451 let v = spec.validate();
3452 assert!(v.valid, "errors: {:?}", v.errors);
3453 assert!(
3454 v.warnings.iter().all(|w| !w.contains("can never latch")),
3455 "computed key covers the guard read: {:?}",
3456 v.warnings
3457 );
3458
3459 let mut dangling = spec.clone();
3460 dangling.computed[0].from =
3461 serde_json::from_value(json!({"gt": [{"key": "scoer"}, {"const": 0.5}]})).unwrap();
3462 let v = dangling.validate();
3463 assert!(
3464 v.warnings
3465 .iter()
3466 .any(|w| w.contains("computed 'high_risk' reads state key 'scoer'"))
3467 );
3468 }
3469
3470 #[test]
3471 fn remember_requires_the_memory_section() {
3472 let spec = SessionSpec::from_value(json!({
3473 "instruction": "x",
3474 "flow": {"steps": [{"id": "only", "terminal": true}]},
3475 "patterns": [{"name": "note", "when": {"is_true": "flag"}, "turns": 2,
3476 "effects": [{"remember": "caller likes {state.thing}"}]}]
3477 }))
3478 .expect("parses");
3479 let v = spec.validate();
3480 assert!(!v.valid);
3481 assert!(v.errors.iter().any(|e| e.contains("no `memory` section")));
3482 }
3483
3484 #[test]
3485 fn memory_slots_join_written_keys_and_reject_derived_targets() {
3486 let spec = SessionSpec::from_value(json!({
3487 "instruction": "x",
3488 "memory": {"slots": [{"predicate": "dietary_identity", "to": "user:diet"}]},
3489 "flow": {"steps": [
3490 {"id": "plan", "posture": "Plan dinner.",
3491 "done": {"is_set": "user:diet"}}
3492 ]}
3493 }))
3494 .expect("parses");
3495 let v = spec.validate();
3496 assert!(v.valid, "errors: {:?}", v.errors);
3497 assert!(v.warnings.iter().all(|w| !w.contains("can never latch")));
3498
3499 let mut bad = spec.clone();
3500 bad.memory.as_mut().unwrap().slots[0].to = "derived:diet".into();
3501 assert!(
3502 bad.validate()
3503 .errors
3504 .iter()
3505 .any(|e| e.contains("read-only key"))
3506 );
3507 }
3508
3509 #[test]
3510 fn memory_section_requires_a_binding_at_apply() {
3511 let spec = SessionSpec::from_value(json!({
3512 "instruction": "x",
3513 "memory": {},
3514 "flow": {"steps": [{"id": "only", "terminal": true}]}
3515 }))
3516 .expect("parses");
3517 let err = spec
3518 .apply(Live::builder(), &State::new(), &SpecResources::default())
3519 .err()
3520 .expect("memory binding required");
3521 assert!(err.contains("SpecResources.memory"));
3522
3523 struct NullBinding;
3524 impl MemoryBinding for NullBinding {
3525 fn install(&self, live: Live, _memory: &MemorySpec) -> Live {
3526 live
3527 }
3528 fn remember(&self, _note: String) {}
3529 }
3530 let resources = SpecResources {
3531 memory: Some(Arc::new(NullBinding)),
3532 ..Default::default()
3533 };
3534 assert!(
3535 spec.apply(Live::builder(), &State::new(), &resources)
3536 .is_ok()
3537 );
3538 }
3539
3540 #[test]
3541 fn state_dictionary_seeds_defaults_and_flags_undeclared_writes() {
3542 let spec = SessionSpec::from_value(json!({
3543 "instruction": "x",
3544 "state": {
3545 "attempts": {"type": "number", "default": 0,
3546 "description": "Verification attempts so far."},
3547 "verified": {"type": "boolean", "default": "yes"}
3548 },
3549 "tools": [{"name": "verify", "set_state": {"verified": true, "vip": true}}],
3550 "flow": {"steps": [
3551 {"id": "v", "posture": "Verify.", "allow": ["verify"],
3552 "done": {"is_true": "verified"}}
3553 ]}
3554 }))
3555 .expect("parses");
3556 let v = spec.validate();
3557 assert!(v.valid, "errors: {:?}", v.errors);
3558 assert!(
3559 v.warnings
3560 .iter()
3561 .any(|w| w.contains("'verified' declares type Boolean")),
3562 "type-mismatched default warns: {:?}",
3563 v.warnings
3564 );
3565 assert!(
3566 v.warnings
3567 .iter()
3568 .any(|w| w.contains("'vip' is written but not declared")),
3569 "undeclared write warns: {:?}",
3570 v.warnings
3571 );
3572
3573 let state = State::new();
3574 spec.seed_state_defaults(&state);
3575 assert_eq!(state.get::<i64>("attempts"), Some(0));
3576 }
3577
3578 #[test]
3579 fn runtime_section_lowers_onto_the_builder() {
3580 let spec = SessionSpec::from_value(json!({
3581 "instruction": "x",
3582 "flow": {"steps": [{"id": "only", "terminal": true}]},
3583 "runtime": {
3584 "temperature": 0.4,
3585 "thinking_budget": 1024,
3586 "include_thoughts": true,
3587 "transcription": {"input": true, "output": false},
3588 "proactive_audio": true,
3589 "vad": {"start_sensitivity": "high", "silence_duration_ms": 400},
3590 "soft_turn_timeout_ms": 1500,
3591 "steering": "context_injection",
3592 "context_delivery": "deferred",
3593 "repair": {"nudge_after": 2, "escalate_after": 5},
3594 "persistence": "memory",
3595 "session_id": "user-1",
3596 "lossy_audio": true
3597 }
3598 }))
3599 .expect("parses");
3600 let v = spec.validate();
3601 assert!(v.valid, "errors: {:?}", v.errors);
3602 assert!(
3603 spec.apply(Live::builder(), &State::new(), &SpecResources::default())
3604 .is_ok()
3605 );
3606
3607 let mut incoherent = spec.clone();
3608 incoherent.runtime.as_mut().unwrap().thinking_budget = None;
3609 assert!(
3610 incoherent
3611 .validate()
3612 .warnings
3613 .iter()
3614 .any(|w| w.contains("include_thoughts"))
3615 );
3616 }
3617
3618 #[test]
3619 fn context_update_steering_lowers_onto_the_builder() {
3620 let spec = SessionSpec::from_value(json!({
3621 "instruction": "x",
3622 "flow": {"steps": [{"id": "only", "terminal": true}]},
3623 "runtime": {"steering": "context_update"}
3624 }))
3625 .expect("parses");
3626 assert!(spec.validate().valid);
3627 let live = spec
3628 .apply(Live::builder(), &State::new(), &SpecResources::default())
3629 .expect("applies");
3630 assert_eq!(
3631 live.describe_contract().controls.steering_mode,
3632 "ContextUpdate"
3633 );
3634 assert!(
3635 spec.to_rust()
3636 .contains(".steering_mode(SteeringMode::ContextUpdate)"),
3637 "codegen emits the same mode"
3638 );
3639 }
3640
3641 #[test]
3642 fn background_tools_and_scheduling_parse_and_apply() {
3643 let spec = SessionSpec::from_value(json!({
3644 "instruction": "x",
3645 "tools": [
3646 {"name": "search_kb", "background": true},
3647 {"name": "log_event", "scheduling": "silent"}
3648 ],
3649 "flow": {"steps": [
3650 {"id": "s", "posture": "Serve.", "allow": ["search_kb", "log_event"],
3651 "done": {"called_ok": "search_kb"}}
3652 ]}
3653 }))
3654 .expect("parses");
3655 assert!(spec.validate().valid);
3656 assert!(
3657 spec.apply(Live::builder(), &State::new(), &SpecResources::default())
3658 .is_ok()
3659 );
3660 }
3661
3662 #[test]
3663 fn a_sandboxed_spec_reaches_only_what_the_operator_allows() {
3664 let spec = SessionSpec::from_value(json!({
3665 "name": "posted",
3666 "mcp": ["rm -rf /", "https://mcp.example.com/sse"],
3667 "tools": [
3668 { "name": "ok", "http": { "url": "https://api.example.com/v1/{args.id}" } },
3669 { "name": "internal", "http": { "url": "http://169.254.169.254/latest/meta-data" } },
3670 { "name": "host_from_args", "http": { "url": "https://{args.host}/x" } },
3671 { "name": "mock", "response": { "ok": true } }
3672 ]
3673 }))
3674 .unwrap();
3675
3676 let (nothing, notes) = spec.sandboxed(&BindingAllowlist::default());
3677 assert!(nothing.mcp.is_empty());
3678 assert!(nothing.tools.iter().all(|t| t.http.is_none()));
3679 assert_eq!(notes.len(), 5, "{notes:?}");
3680
3681 let allow = BindingAllowlist::default()
3682 .allow_http_prefix("https://api.example.com")
3683 .allow_mcp("https://mcp.example.com/sse");
3684 let (some, notes) = spec.sandboxed(&allow);
3685 assert_eq!(some.mcp, ["https://mcp.example.com/sse"]);
3686 let bound: Vec<&str> = some
3687 .tools
3688 .iter()
3689 .filter(|t| t.http.is_some())
3690 .map(|t| t.name.as_str())
3691 .collect();
3692 assert_eq!(bound, ["ok"]);
3693 assert_eq!(notes.len(), 3, "{notes:?}");
3694
3695 let tricky = BindingAllowlist::default().allow_http_prefix("https://api.example.com");
3697 assert!(!tricky.allows_http("https://api.example.com.evil.net/x"));
3698 assert!(!tricky.allows_http("https://api.example.com@evil.net/x"));
3699 assert!(!tricky.allows_http("https://api.example.com:8443/x"));
3700 assert!(!tricky.allows_http("http://api.example.com/x"));
3701
3702 let subtree = BindingAllowlist::default().allow_http_prefix("https://api.example.com/v2/");
3704 assert!(subtree.allows_http("https://API.example.com/v2/orders/{args.id}"));
3705 assert!(!subtree.allows_http("https://api.example.com/v2/../admin"));
3706 assert!(!subtree.allows_http("https://api.example.com/v2/%2e%2e/admin"));
3707 assert!(!subtree.allows_http("https://api.example.com/v2/%2E%2E/admin"));
3708 }
3709
3710 #[cfg(feature = "http-tools")]
3711 #[tokio::test]
3712 async fn a_sandboxed_binding_is_checked_again_when_it_runs() {
3713 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3714
3715 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3718 let origin = format!("http://{}", listener.local_addr().unwrap());
3719 tokio::spawn(async move {
3720 while let Ok((mut socket, _)) = listener.accept().await {
3721 let mut buf = vec![0u8; 4096];
3722 let n = socket.read(&mut buf).await.unwrap_or(0);
3723 let request = String::from_utf8_lossy(&buf[..n]).to_string();
3724 let path = request.split_whitespace().nth(1).unwrap_or("/").to_string();
3725 let response = if path == "/v2/hop" {
3726 "HTTP/1.1 302 Found\r\nlocation: /admin\r\ncontent-length: 0\r\nconnection: close\r\n\r\n".to_string()
3727 } else {
3728 let body = json!({ "path": path }).to_string();
3729 format!(
3730 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
3731 body.len()
3732 )
3733 };
3734 let _ = socket.write_all(response.as_bytes()).await;
3735 }
3736 });
3737
3738 let spec = SessionSpec::from_value(json!({
3739 "name": "posted",
3740 "tools": [{ "name": "get", "http": { "url": format!("{origin}/v2/{{args.path}}") } }]
3741 }))
3742 .unwrap();
3743 let allow = BindingAllowlist::default().allow_http_prefix(format!("{origin}/v2/"));
3744 let (sandboxed, notes) = spec.sandboxed(&allow);
3745 assert!(notes.is_empty(), "{notes:?}");
3746 let state = State::new();
3747 let dispatcher = sandboxed.build_dispatcher(&state);
3748
3749 let ok = dispatcher
3750 .call_function("get", json!({ "path": "orders" }))
3751 .await
3752 .unwrap();
3753 assert_eq!(ok["path"], "/v2/orders");
3754 let climbed = dispatcher
3756 .call_function("get", json!({ "path": "../admin" }))
3757 .await;
3758 assert!(climbed.is_err(), "{climbed:?}");
3759 let redirected = dispatcher
3761 .call_function("get", json!({ "path": "hop" }))
3762 .await;
3763 assert!(redirected.is_err(), "{redirected:?}");
3764
3765 let trusted = spec.build_dispatcher(&state);
3767 let followed = trusted
3768 .call_function("get", json!({ "path": "hop" }))
3769 .await
3770 .unwrap();
3771 assert_eq!(followed["path"], "/admin");
3772 }
3773
3774 fn booking_bundle() -> SessionSpec {
3777 let conversation: Value =
3778 serde_json::from_str(include_str!("../../../../conversations/booking.spec.json"))
3779 .unwrap();
3780 let scenario = |file: &str| -> Value { serde_json::from_str(file).unwrap() };
3781 SessionSpec::from_value(json!({
3782 "name": "booking",
3783 "modality": "audio",
3784 "tools": [{
3785 "name": "book",
3786 "description": "Book the table",
3787 "response": { "confirmation": "B-1" }
3788 }],
3789 "conversation": conversation,
3790 "scenarios": [
3791 scenario(include_str!("../../../../conversations/booking.happy.scenario.json")),
3792 scenario(include_str!(
3793 "../../../../conversations/booking.no_book_without_confirm.scenario.json"
3794 )),
3795 ]
3796 }))
3797 .unwrap()
3798 }
3799
3800 #[test]
3801 fn tools_used_only_in_a_digression_are_referenced() {
3802 let mut spec = booking_bundle();
3803 spec.tools
3804 .push(serde_json::from_value(json!({ "name": "transfer" })).unwrap());
3805 let unreferenced = |spec: &SessionSpec| {
3806 spec.validate()
3807 .warnings
3808 .iter()
3809 .any(|w| w.contains("'transfer' is declared but no step"))
3810 };
3811 assert!(unreferenced(&spec));
3812 spec.conversation.as_mut().unwrap().overlays = serde_json::from_value(json!([{
3813 "name": "handoff",
3814 "trigger": { "is_true": "intent:human_agent" },
3815 "stages": [{ "id": "transfer", "allow": ["transfer"], "done": { "called_ok": "transfer" } }],
3816 "resume": "terminate"
3817 }]))
3818 .unwrap();
3819 assert!(!unreferenced(&spec));
3820 }
3821
3822 #[test]
3823 fn a_conversation_spec_validates_like_a_flow() {
3824 let spec = booking_bundle();
3825 let report = spec.validate();
3826 assert!(report.valid, "{:?}", report.errors);
3827 let unwritten: Vec<&String> = report
3830 .warnings
3831 .iter()
3832 .filter(|w| w.contains("no tool, extractor"))
3833 .collect();
3834 assert_eq!(unwritten.len(), 1, "{:?}", report.warnings);
3835 assert!(unwritten[0].contains("user_confirmed"));
3836 assert!(report.mermaid.contains("confirm"), "{}", report.mermaid);
3837 assert!(report.tools.contains(&"book".to_string()));
3838
3839 let mut both = spec.clone();
3841 both.flow = Some(Flow::default());
3842 assert!(!both.validate().valid);
3843
3844 let mut resolving = spec;
3846 resolving.conversation.as_mut().unwrap().stages[0]
3847 .resolve
3848 .push(crate::conversation::ResolveSpec {
3849 slot: "availability".into(),
3850 resolver: None,
3851 args: vec![],
3852 ttl_secs: None,
3853 });
3854 let report = resolving.validate();
3855 assert!(
3856 report.errors.iter().any(|e| e.contains("availability")),
3857 "{:?}",
3858 report.errors
3859 );
3860 }
3861
3862 #[tokio::test]
3863 async fn a_conversation_spec_runs_its_scenarios_and_applies() {
3864 let spec = booking_bundle();
3865 let reports = spec.run_scenarios().await;
3866 assert_eq!(reports.len(), 2);
3867 assert!(reports.iter().all(|r| r.passed), "{reports:?}");
3868
3869 let mut broken = spec.clone();
3870 broken.scenarios[0]
3871 .steps
3872 .push(crate::simulation::SimStep::ExpectActive(vec![
3873 "nowhere".into(),
3874 ]));
3875 assert!(!broken.run_scenarios().await[0].passed);
3876
3877 spec.apply(Live::builder(), &State::new(), &SpecResources::default())
3878 .expect("a conversation spec applies");
3879 }
3880
3881 fn booking_tool(extra: Value) -> SessionSpec {
3882 let mut tool = json!({
3883 "name": "book",
3884 "description": "Book the table",
3885 "response": { "confirmation": "MOCK" },
3886 "set_state": { "booked": true },
3887 "save_response_as": "booking"
3888 });
3889 tool.as_object_mut()
3890 .unwrap()
3891 .extend(extra.as_object().unwrap().clone());
3892 SessionSpec::from_value(json!({
3893 "name": "t",
3894 "tools": [tool],
3895 "flow": { "steps": [{ "id": "s", "allow": ["book"] }] }
3896 }))
3897 .unwrap()
3898 }
3899
3900 #[tokio::test]
3901 async fn an_implementation_replaces_the_call_not_the_declaration() {
3902 let spec = booking_tool(json!({}));
3903 let state = State::new();
3904 let resources = SpecResources::default().implement(gemini_adk_rs::tool::SimpleTool::new(
3905 "book",
3906 "real booking",
3907 None,
3908 |_| async { Ok(json!({ "confirmation": "REAL-7" })) },
3909 ));
3910 let dispatcher = spec.build_dispatcher_with(&state, &resources);
3911 let out = dispatcher.call_function("book", json!({})).await.unwrap();
3912 assert_eq!(out["confirmation"], "REAL-7");
3913 assert_eq!(state.get::<bool>("booked"), Some(true));
3915 assert_eq!(
3916 state.get::<Value>("booking").unwrap()["confirmation"],
3917 "REAL-7"
3918 );
3919 assert_eq!(
3921 dispatcher.to_tool_declarations()[0]
3922 .function_declarations
3923 .as_ref()
3924 .unwrap()[0]
3925 .description,
3926 "Book the table"
3927 );
3928
3929 let stray = SpecResources::default().implement(gemini_adk_rs::tool::SimpleTool::new(
3931 "refund",
3932 "",
3933 None,
3934 |_| async { Ok(json!({})) },
3935 ));
3936 assert!(spec.apply(Live::builder(), &state, &stray).is_err());
3937 }
3938
3939 #[cfg(unix)]
3940 #[tokio::test]
3941 async fn an_mcp_binding_calls_the_tool_on_that_server() {
3942 let dir = std::env::temp_dir().join(format!("mcp-bind-{}", std::process::id()));
3944 std::fs::create_dir_all(&dir).unwrap();
3945 let script = dir.join("server.sh");
3946 std::fs::write(
3947 &script,
3948 r#"while IFS= read -r line; do
3949 id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')
3950 [ -z "$id" ] && continue
3951 case "$line" in
3952 *'"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"t","version":"1"}}}\n' "$id" ;;
3953 *'"tools/call"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"{\\"confirmation\\":\\"MCP-1\\"}"}]}}\n' "$id" ;;
3954 *) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
3955 esac
3956done
3957"#,
3958 )
3959 .unwrap();
3960 let spec = booking_tool(json!({ "mcp": format!("sh {}", script.display()) }));
3961 let state = State::new();
3962 let dispatcher = spec.build_dispatcher_with(&state, &SpecResources::default());
3963 let out = dispatcher
3964 .call_function("book", json!({ "party": 2 }))
3965 .await
3966 .unwrap();
3967 assert_eq!(out, json!({ "confirmation": "MCP-1" }));
3968 assert_eq!(state.get::<bool>("booked"), Some(true));
3969
3970 let both = booking_tool(json!({
3972 "mcp": "x",
3973 "http": { "url": "https://api.example.com/book" }
3974 }));
3975 assert!(!both.validate().valid);
3976
3977 let (sandboxed, notes) = spec.sandboxed(&BindingAllowlist::default());
3979 assert!(sandboxed.tools[0].mcp.is_none());
3980 assert_eq!(notes.len(), 1, "{notes:?}");
3981 let _ = std::fs::remove_dir_all(dir);
3982 }
3983
3984 #[test]
3985 fn mcp_results_become_plain_values() {
3986 assert_eq!(
3987 mcp_value(json!({ "structuredContent": { "a": 1 }, "content": [] })),
3988 json!({ "a": 1 })
3989 );
3990 assert_eq!(
3991 mcp_value(json!({ "content": [{ "type": "text", "text": "{\"a\":2}" }] })),
3992 json!({ "a": 2 })
3993 );
3994 assert_eq!(
3995 mcp_value(json!({ "content": [{ "type": "text", "text": "done" }] })),
3996 json!({ "output": "done" })
3997 );
3998 }
3999
4000 #[test]
4001 fn extraction_runs_on_the_model_the_spec_names() {
4002 use gemini_adk_rs::llm::{LlmRegistry, MockLlm};
4003 let mut spec = collections_spec();
4004 let mut second = spec.extract[0].clone();
4005 second.name = "second".into();
4006 spec.extract.push(second);
4007 spec.models.extraction = Some("fast-lite".into());
4008 spec.extract[0].model = Some("fast-full".into());
4009 assert!(!spec.uses_default_extraction_model());
4010 assert!(
4011 spec.validate()
4012 .warnings
4013 .iter()
4014 .all(|w| !w.contains("models.extraction")),
4015 "{:?}",
4016 spec.validate().warnings
4017 );
4018
4019 let mut registry = LlmRegistry::new();
4020 registry.register("fast", |name| {
4021 Arc::new(MockLlm::text("{}").with_model_id(name)) as Arc<dyn BaseLlm>
4022 });
4023 let resources = SpecResources {
4024 models: Some(Arc::new(registry)),
4025 ..SpecResources::default()
4026 };
4027 let mut cache = BTreeMap::new();
4028 let ids: Vec<String> = spec
4029 .extract
4030 .iter()
4031 .map(|e| {
4032 extraction_llm_for(e, spec.models.extraction.as_deref(), &resources, &mut cache)
4033 .unwrap()
4034 .model_id()
4035 .to_string()
4036 })
4037 .collect();
4038 assert_eq!(ids[0], "fast-full", "an entry's model wins");
4039 assert!(ids[1..].iter().all(|id| id == "fast-lite"), "{ids:?}");
4040 assert_eq!(cache.len(), 2, "one model per name");
4041
4042 spec.apply(Live::builder(), &State::new(), &resources)
4044 .expect("applies on the named models");
4045 }
4046
4047 #[tokio::test]
4048 async fn an_entry_or_the_spec_sets_the_thinking_budget() {
4049 use gemini_adk_rs::live::TurnExtractor;
4050 use gemini_adk_rs::llm::{LlmResponse, MockLlm};
4051 let budgets = Arc::new(parking_lot::Mutex::new(Vec::new()));
4052 let seen = budgets.clone();
4053 let llm: Arc<dyn BaseLlm> = Arc::new(MockLlm::from_fn(move |req| {
4054 seen.lock().push(req.thinking_budget);
4055 Ok(LlmResponse::from_text("{}"))
4056 }));
4057 let window = [gemini_adk_rs::live::TranscriptTurn {
4058 turn_number: 0,
4059 user: "I need a refill of my lisinopril.".into(),
4060 model: String::new(),
4061 tool_calls: Vec::new(),
4062 timestamp: std::time::Instant::now(),
4063 }];
4064 let entry = collections_spec().extract[0].clone();
4065 let models = ModelsSpec {
4066 extraction: None,
4067 extraction_thinking_budget: Some(64),
4068 };
4069 let mut own = entry.clone();
4070 own.thinking_budget = Some(8);
4071 for (e, m) in [
4072 (&entry, &models),
4073 (&own, &models),
4074 (&entry, &ModelsSpec::default()),
4075 ] {
4076 compile_extractor(e, llm.clone(), m)
4077 .extract(&window)
4078 .await
4079 .unwrap();
4080 }
4081 assert_eq!(*budgets.lock(), [Some(64), Some(8), Some(0)]);
4082 }
4083
4084 #[test]
4085 fn unnamed_extraction_warns_and_an_unknown_model_fails() {
4086 let unnamed = collections_spec();
4087 assert!(unnamed.uses_default_extraction_model());
4088 assert!(
4089 unnamed
4090 .validate()
4091 .warnings
4092 .iter()
4093 .any(|w| w.contains("set models.extraction")),
4094 "{:?}",
4095 unnamed.validate().warnings
4096 );
4097
4098 let mut unknown = collections_spec();
4099 unknown.models.extraction = Some("gemma-decide".into());
4100 let err = unknown
4101 .apply(Live::builder(), &State::new(), &SpecResources::default())
4102 .err()
4103 .expect("nothing resolves gemma-decide");
4104 assert!(err.contains("register it in SpecResources.models"), "{err}");
4105
4106 let mut empty = collections_spec();
4107 empty.models.extraction = Some(" ".into());
4108 assert!(!empty.validate().valid);
4109 }
4110
4111 #[test]
4112 fn apply_configures_a_builder() {
4113 let spec = collections_spec();
4114 let state = State::new();
4115 let err = spec
4117 .apply(Live::builder(), &state, &SpecResources::default())
4118 .err()
4119 .expect("requires extraction llm");
4120 assert!(err.contains("extraction_llm"));
4121
4122 let mut no_extract = spec.clone();
4124 no_extract.extract.clear();
4125 assert!(
4126 no_extract
4127 .apply(Live::builder(), &state, &SpecResources::default())
4128 .is_ok()
4129 );
4130 }
4131}