Skip to main content

gemini_adk_fluent_rs/spec/
mod.rs

1//! `SessionSpec` — a whole Live session as one serializable JSON document.
2//!
3//! Where [`Flow`] made the *governance DAG* data, `SessionSpec` makes the
4//! *application* data: session framing (instruction, greeting, modality),
5//! declarative tool bindings (mock, HTTP, MCP), schema-as-JSON extraction that
6//! fills the state guards read, data-driven phases and watchers over the same
7//! closed [`Guard`] vocabulary, reusable flow fragments, and an embedded test
8//! suite that replays scripted conversations through the real
9//! [`FlowStack`](gemini_adk_rs::flow::FlowStack) offline.
10//!
11//! The invariants:
12//! - **What serializes, runs.** [`SessionSpec::apply`] configures a
13//!   [`Live`] builder from the document; nothing in the document needs Rust.
14//! - **What can fail, fails at load time.** [`SessionSpec::validate`] runs the
15//!   flow compiler, cross-checks tool names, and diffs the state keys guards
16//!   *read* against the keys the session *writes* — the flow-level analogue of
17//!   `compile_with_tools` for the dominant silent failure in data-authored
18//!   flows (a guard waiting on a key nothing sets).
19//! - **The escape hatches stay in code.** Custom closures (guards, tools,
20//!   callbacks) are added on the returned builder after `apply`, exactly as
21//!   before; the spec never pretends to serialize them.
22
23pub 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/// Output modality for a spec-driven session.
68#[derive(
69    Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
70)]
71#[serde(rename_all = "lowercase")]
72pub enum SpecModality {
73    /// Text-only session (the default — no microphone needed).
74    #[default]
75    Text,
76    /// Audio (voice) session.
77    Audio,
78}
79
80/// An HTTP binding for a declared tool: the call is executed as an HTTP
81/// request with `{args.field}` / `{state.key}` interpolation in the URL,
82/// headers, and body strings, and the JSON response is returned to the model.
83///
84/// Requires the `http-tools` feature; without it, validation reports the
85/// binding as unsupported instead of failing silently at call time.
86#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
87pub struct HttpBinding {
88    /// HTTP method (GET, POST, PUT, PATCH, DELETE). Default GET.
89    #[serde(default = "default_method")]
90    pub method: String,
91    /// Request URL, with `{args.*}`/`{state.*}` interpolation.
92    pub url: String,
93    /// Request headers, values interpolated.
94    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
95    pub headers: BTreeMap<String, String>,
96    /// JSON body; every string value is interpolated. Omit for no body.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub body: Option<Value>,
99    /// Set by [`SessionSpec::sandboxed`]: the request URL (after
100    /// interpolation) and every redirect target must stay inside it.
101    #[serde(skip)]
102    #[schemars(skip)]
103    pub(crate) reach: Option<BindingAllowlist>,
104}
105
106fn default_method() -> String {
107    "GET".to_string()
108}
109
110/// A declared tool. Without an `http` binding it is a **mock**: it returns
111/// `response` (default `{"ok": true}`) and writes `set_state` — enough to
112/// model, validate, and demo a governed conversation before any real tool
113/// exists. With `http` it performs the request instead (and still applies
114/// `set_state` afterwards, so guards latch identically) — swap a mock for a
115/// binding without touching the flow.
116#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
117pub struct ToolSpec {
118    /// Tool (function) name the model calls.
119    pub name: String,
120    /// Description shown to the model.
121    #[serde(default)]
122    pub description: String,
123    /// JSON Schema for the arguments (Gemini subset). `None` = no parameters.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub parameters: Option<Value>,
126    /// Canned JSON response (mock tools). Default `{"ok": true}`.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub response: Option<Value>,
129    /// JSON Schema of what the tool returns. Code mode shows it in the
130    /// function's docstring, so a program reads the right keys; a mock tool
131    /// without it shows the shape of its `response`.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub returns: Option<Value>,
134    /// State keys written when the tool runs — how a tool latches guards.
135    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
136    pub set_state: BTreeMap<String, Value>,
137    /// Store the tool's full response under this state key.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub save_response_as: Option<String>,
140    /// Execute as an HTTP request instead of returning the canned response.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub http: Option<HttpBinding>,
143    /// Execute by calling the tool of the same name on this MCP server: a
144    /// command line (stdio) or an `http(s)://` URL. This is how a tool
145    /// written in another language (a generated Python or Go tool server)
146    /// implements a declared tool. The declaration here stays what the model
147    /// sees, and `set_state` still applies.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub mcp: Option<String>,
150    /// Run non-blocking: the model keeps speaking while the tool executes
151    /// (`behavior: NonBlocking` on the wire; Google AI only, stripped on
152    /// Vertex). Implied by `scheduling`.
153    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
154    pub background: bool,
155    /// How the async response is delivered (implies `background`).
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub scheduling: Option<SchedulingSpec>,
158}
159
160/// Delivery mode for a background tool's response.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
162#[serde(rename_all = "snake_case")]
163pub enum SchedulingSpec {
164    /// Halt current output and report immediately.
165    Interrupt,
166    /// Wait until the model finishes its current output.
167    WhenIdle,
168    /// Integrate silently without notifying the user.
169    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/// How extracted fields are promoted into bare state keys.
183#[derive(
184    Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
185)]
186#[serde(rename_all = "snake_case")]
187pub enum PromotePolicy {
188    /// Write once, never overwrite a known value (default).
189    #[default]
190    KeepKnown,
191    /// Always overwrite.
192    Overwrite,
193    /// Promote only when the extracted value is `true`.
194    TrueOnly,
195    /// Promote only non-empty values.
196    NonEmpty,
197}
198
199/// Promote one extracted field into a session state key, where flow guards
200/// (`captured`, `is_true`, …) read it.
201#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
202pub struct PromoteSpec {
203    /// Field name in the extraction result.
204    pub field: String,
205    /// Target state key. Defaults to the field name.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub to: Option<String>,
208    /// Merge policy.
209    #[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/// When an extractor runs.
233#[derive(
234    Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
235)]
236#[serde(rename_all = "snake_case")]
237pub enum TriggerSpec {
238    /// After every turn (default).
239    #[default]
240    EveryTurn,
241    /// After tool calls complete.
242    AfterToolCall,
243    /// On generation complete, before the turn completes.
244    OnGenerationComplete,
245    /// When a phase transition occurs.
246    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/// Schema-as-JSON out-of-band extraction: an OOB model fills `schema` from the
261/// transcript, the result lands in state under `name`, and `promote` rules
262/// write individual fields to bare keys — closing the loop that lets a flow
263/// advance from *speech alone* (`captured` guards latch with no tool call).
264#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
265pub struct ExtractSpec {
266    /// Extraction name — the state key the full result is stored under.
267    pub name: String,
268    /// Instruction for the extraction model.
269    pub instruction: String,
270    /// JSON Schema the extraction must satisfy.
271    pub schema: Value,
272    /// Transcript window in turns. Default 3.
273    #[serde(default = "default_window")]
274    pub window: usize,
275    /// When to run.
276    #[serde(default)]
277    pub trigger: TriggerSpec,
278    /// Field-promotion rules into bare state keys.
279    #[serde(default, skip_serializing_if = "Vec::is_empty")]
280    pub promote: Vec<PromoteSpec>,
281    /// The text model this entry runs on, such as `gemini-3.5-flash-lite`.
282    /// Overrides `models.extraction`.
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub model: Option<String>,
285    /// The thinking budget this entry's requests send. Overrides
286    /// `models.extraction_thinking_budget`.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub thinking_budget: Option<u32>,
289}
290
291/// The extraction model `adk spec check` suggests pinning, with
292/// [`RECOMMENDED_EXTRACTION_THINKING_BUDGET`]. On the labelled pharmacy turn
293/// it was correct in 60 of 60 rounds at 0.67 s median and 1.2 s at most, where
294/// the rolling `gemini-flash-latest` default took 6.7 s at the median and up
295/// to 62 s (`tests/extraction_latency.rs`). Without thinking it follows an
296/// instruction literally: say what counts, not "leave it out until".
297pub const RECOMMENDED_EXTRACTION_MODEL: &str = "gemini-3.5-flash-lite";
298
299/// The thinking budget pinned with [`RECOMMENDED_EXTRACTION_MODEL`], which
300/// rejects 0 and does not think below about 1024.
301pub const RECOMMENDED_EXTRACTION_THINKING_BUDGET: u32 =
302    gemini_adk_rs::live::extractor::FALLBACK_THINKING_BUDGET;
303
304/// What validation says when extraction names no model.
305const 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/// The models a spec runs on, by role.
310#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
311pub struct ModelsSpec {
312    /// The text model `extract` entries run on, such as
313    /// `gemini-3.5-flash-lite`, unless an entry names its own. Name one: the
314    /// host default is the rolling `gemini-flash-latest` alias, whose model
315    /// (and latency) changes under you, and every turn waits for extraction.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub extraction: Option<String>,
318    /// The thinking budget extraction requests send. The default, 0, keeps
319    /// thinking off; a model that rejects 0 (`gemini-3.5-flash-lite` needs
320    /// at least 1) is retried at 64, then with no budget. Set 64 for such a
321    /// model to skip the rejected first request.
322    #[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/// A serializable side effect for phase entry, watcher, and pattern actions —
331/// the closed-effect counterpart to [`Guard`]'s closed predicates. One
332/// vocabulary, honored identically wherever effects fire.
333#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
334#[serde(rename_all = "snake_case")]
335pub enum EffectSpec {
336    /// Write these state keys.
337    Set(BTreeMap<String, Value>),
338    /// Inject a model-role context turn (steering text the model reads before
339    /// its next response — it does not answer it directly).
340    Context(String),
341    /// Inject the text as a model-role turn **and** ask the model to respond
342    /// now — the "make the model speak" effect (proactive check-in, nudge).
343    Prompt(String),
344    /// Durably remember a note (`{state.key}` templates interpolated) through
345    /// the session's memory binding. Requires the spec's `memory` section.
346    Remember(String),
347}
348
349/// A data-driven phase transition: fire `when` the guard holds over state.
350///
351/// Guards here evaluate against state alone (no flow marking), so
352/// `called_ok`/`done` atoms are rejected by validation — use a state key a
353/// tool or extractor writes instead.
354#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
355pub struct TransitionSpec {
356    /// Target phase.
357    pub to: String,
358    /// Condition over session state.
359    pub when: Guard,
360    /// Optional description for navigation steering.
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub description: Option<String>,
363}
364
365/// A data-driven conversation phase.
366#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
367pub struct PhaseSpec {
368    /// Phase name.
369    pub name: String,
370    /// Instruction while this phase is active.
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub instruction: Option<String>,
373    /// Tool names available in this phase.
374    #[serde(default, skip_serializing_if = "Vec::is_empty")]
375    pub tools: Vec<String>,
376    /// Required state keys (drives conversation repair).
377    #[serde(default, skip_serializing_if = "Vec::is_empty")]
378    pub needs: Vec<String>,
379    /// Effects fired on phase entry.
380    #[serde(default, skip_serializing_if = "Vec::is_empty")]
381    pub on_enter: Vec<EffectSpec>,
382    /// Guarded transitions out of this phase.
383    #[serde(default, skip_serializing_if = "Vec::is_empty")]
384    pub transitions: Vec<TransitionSpec>,
385    /// Prompt the model on entry.
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub prompt_on_enter: Option<bool>,
388    /// Terminal phase.
389    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
390    pub terminal: bool,
391}
392
393/// A data-driven state watcher condition.
394#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
395#[serde(rename_all = "snake_case")]
396pub enum WatchCondition {
397    /// Any change.
398    Changed,
399    /// Changed to exactly this value.
400    ChangedTo(Value),
401    /// Numeric value crossed above the threshold.
402    CrossedAbove(f64),
403    /// Numeric value crossed below the threshold.
404    CrossedBelow(f64),
405    /// Became `true`.
406    BecameTrue,
407    /// Became `false`.
408    BecameFalse,
409}
410
411/// A data-driven state watcher: when `key` satisfies the condition, run the
412/// effects. Watchers receive the live session writer, so the full
413/// [`EffectSpec`] vocabulary applies — a watcher can set state, inject
414/// context, prompt the model, or remember durably.
415#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
416pub struct WatchSpec {
417    /// Watched state key.
418    pub key: String,
419    /// Trigger condition.
420    pub condition: WatchCondition,
421    /// State keys written when it fires (sugar for an [`EffectSpec::Set`]).
422    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
423    pub set: BTreeMap<String, Value>,
424    /// Effects fired in order after `set`.
425    #[serde(default, skip_serializing_if = "Vec::is_empty")]
426    pub effects: Vec<EffectSpec>,
427}
428
429/// A data-driven temporal pattern: fire effects when a state condition holds
430/// continuously — for a duration (`sustained_secs`) or a number of
431/// consecutive turns (`turns`). Exactly one of the two must be set.
432///
433/// This is the "the caller has sounded confused for 30 seconds" /
434/// "we've been stuck on this for 3 turns" reactor, as data.
435#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
436pub struct PatternSpec {
437    /// Pattern name (diagnostic identity).
438    pub name: String,
439    /// Condition over session state (no marking atoms).
440    pub when: Guard,
441    /// Fire after the condition holds this many seconds.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub sustained_secs: Option<u64>,
444    /// Fire after the condition holds for this many consecutive turns.
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub turns: Option<u32>,
447    /// Effects when the pattern fires (`set` state and/or inject `context`).
448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
449    pub effects: Vec<EffectSpec>,
450}
451
452/// A computed (derived) state variable authored as data: `key` is written to
453/// `derived:{key}` whenever the [`Expr`] evaluates to a value. Dependencies
454/// are inferred from the expression's [`Expr::keys_read`], so the runtime's
455/// dependency-ordered [`ComputedRegistry`](gemini_adk_rs::live::ComputedRegistry)
456/// invariants hold with nothing extra to declare. Guards read the result by
457/// its bare key (the `derived:` fallback).
458#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
459pub struct ComputedSpec {
460    /// Result key (written as `derived:{key}`).
461    pub key: String,
462    /// The expression computing the value.
463    pub from: Expr,
464    /// Human-readable note.
465    #[serde(default, skip_serializing_if = "String::is_empty")]
466    pub description: String,
467}
468
469/// Declared JSON type of a state key.
470#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
471#[serde(rename_all = "snake_case")]
472pub enum StateType {
473    /// JSON boolean.
474    Boolean,
475    /// JSON number.
476    Number,
477    /// JSON string.
478    String,
479    /// JSON object.
480    Object,
481    /// JSON array.
482    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/// One declared state key: its type, meaning, and optional starting value.
499///
500/// The `state` section is the session's data dictionary. Declaring it is
501/// optional, but once present it powers editor autocomplete, key-existence
502/// warnings for every guard/effect/tool reference, typed key constants in
503/// generated code, and `default` seeding at connect.
504#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
505pub struct StateFieldSpec {
506    /// Declared JSON type.
507    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
508    pub kind: Option<StateType>,
509    /// What this key means.
510    #[serde(default, skip_serializing_if = "String::is_empty")]
511    pub description: String,
512    /// Initial value seeded at connect when the key is unset.
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub default: Option<Value>,
515}
516
517/// Project one remembered fact into a governed state slot: when memory holds
518/// a value for `predicate`, it is written to the `to` state key — where
519/// `needs`, `captured`, and every other guard reads it exactly as if the
520/// caller had just said it.
521#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
522pub struct MemorySlotSpec {
523    /// Memory predicate (e.g. `dietary_identity`).
524    pub predicate: String,
525    /// Target state key (must not be `derived:` — that prefix is read-only).
526    pub to: String,
527}
528
529/// The session's durable-memory declaration. Installing it wires the memory
530/// subsystem in through a [`MemoryBinding`] supplied in [`SpecResources`]:
531/// the `recall_context` / `manage_memory` tools (ambient, so step `allow`
532/// lists don't switch recall off), turn ingestion, end-of-session
533/// reconciliation, and the slot projections below. [`EffectSpec::Remember`]
534/// writes through the same binding.
535#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
536pub struct MemorySpec {
537    /// Remembered facts projected into state slots.
538    #[serde(default, skip_serializing_if = "Vec::is_empty")]
539    pub slots: Vec<MemorySlotSpec>,
540}
541
542/// Speech-detection sensitivity for [`VadSpec`].
543#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
544#[serde(rename_all = "snake_case")]
545pub enum SensitivitySpec {
546    /// Fewer false positives; may miss soft speech.
547    Low,
548    /// Balanced.
549    Medium,
550    /// Catches everything; more false positives.
551    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/// Voice-activity-detection tuning — the knobs that decide how eagerly the
565/// session hears speech start and stop.
566#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
567pub struct VadSpec {
568    /// Sensitivity for detecting speech onset.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub start_sensitivity: Option<SensitivitySpec>,
571    /// Sensitivity for detecting end of speech.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub end_sensitivity: Option<SensitivitySpec>,
574    /// Milliseconds of audio kept before speech onset.
575    #[serde(default, skip_serializing_if = "Option::is_none")]
576    pub prefix_padding_ms: Option<u32>,
577    /// Milliseconds of silence before end-of-speech triggers.
578    #[serde(default, skip_serializing_if = "Option::is_none")]
579    pub silence_duration_ms: Option<u32>,
580}
581
582/// Input-audio hardening: the measured mic chain (denoiser, noise gate),
583/// client input-VAD tuning, and interruption authority. Lowers to
584/// `Live::mic_denoise` / `mic_noise_gate` / `input_vad` /
585/// `client_interruption_authority`; see the hardening chapter for the
586/// benchmark behind each default.
587#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
588pub struct AudioSpec {
589    /// Run the RNNoise speech enhancer over incoming user audio (requires
590    /// the `denoise` feature; skipped with a validation warning otherwise).
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    pub denoise: Option<bool>,
593    /// Noise gate after the denoiser — silences frames below a level
594    /// threshold (near-talker preference; rejects denoiser residue).
595    #[serde(default, skip_serializing_if = "Option::is_none")]
596    pub noise_gate: Option<NoiseGateSpec>,
597    /// Client input-VAD tuning (the detector driving speech edges in
598    /// `send_audio`).
599    #[serde(default, skip_serializing_if = "Option::is_none")]
600    pub client_vad: Option<ClientVadSpec>,
601    /// Who decides when user speech interrupts the model.
602    #[serde(default, skip_serializing_if = "Option::is_none")]
603    pub authority: Option<AuthoritySpec>,
604    /// Milliseconds to hold the turn-end marker during mid-turn pauses, suppressing
605    /// false end-of-turn commits. Measured on TurnBench dev: 800 ms = 0.1-fp
606    /// qualifying point (recall 0.798), 1600 ms = recall 0.508 (frontier).
607    #[serde(default, skip_serializing_if = "Option::is_none")]
608    pub eot_hold_ms: Option<u32>,
609    /// Milliseconds to suppress barge-in detection on backchannels and false
610    /// interruptions. Measured on TurnBench dev: 1400 ms suppresses backchannel
611    /// false positives (0.702 → 0.062), 2000 ms = maximum interruption match window.
612    #[serde(default, skip_serializing_if = "Option::is_none")]
613    pub min_interruption_ms: Option<u32>,
614}
615
616/// Noise-gate stage parameters.
617#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
618pub struct NoiseGateSpec {
619    /// RMS threshold in sample units (i16 full scale 32767; measured sweet
620    /// spot 400–700 behind the denoiser).
621    #[serde(default = "default_gate_threshold")]
622    pub threshold_rms: f64,
623    /// Quiet frames the gate stays open after the last loud one.
624    #[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/// Client input-VAD tuning: start from a preset, override individual knobs.
636#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
637pub struct ClientVadSpec {
638    /// Base preset the overrides apply to.
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub preset: Option<ClientVadPreset>,
641    /// Energy above the noise floor (dB) to open.
642    #[serde(default, skip_serializing_if = "Option::is_none")]
643    pub start_threshold_db: Option<f64>,
644    /// Energy above the noise floor (dB) to close.
645    #[serde(default, skip_serializing_if = "Option::is_none")]
646    pub stop_threshold_db: Option<f64>,
647    /// Consecutive frames (30 ms each) to confirm onset.
648    #[serde(default, skip_serializing_if = "Option::is_none")]
649    pub min_speech_frames: Option<u32>,
650    /// Frames of hangover before speech-end.
651    #[serde(default, skip_serializing_if = "Option::is_none")]
652    pub hangover_frames: Option<u32>,
653}
654
655/// Named client-VAD starting points.
656#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
657#[serde(rename_all = "snake_case")]
658pub enum ClientVadPreset {
659    /// The library defaults (quiet environments).
660    Default,
661    /// The closed-loop-tuned noisy-environment profile — use behind
662    /// `denoise: true` (see `VadConfig::noisy_street`).
663    NoisyStreet,
664}
665
666impl ClientVadSpec {
667    /// Lower to a wire `VadConfig`: preset base plus overrides.
668    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/// Interruption authority (measured trade: client is ~2× faster to barge
690/// in; server posted zero false interruptions in every benchmark run).
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
692#[serde(rename_all = "snake_case")]
693pub enum AuthoritySpec {
694    /// The Live API's automatic activity detection decides (default).
695    Server,
696    /// This client's input VAD decides: automatic detection is disabled and
697    /// speech edges send activityStart/activityEnd.
698    Client,
699}
700
701/// Input/output transcription toggles.
702#[derive(Debug, Clone, Copy, Serialize, Deserialize, schemars::JsonSchema)]
703pub struct TranscriptionSpec {
704    /// Transcribe the user's speech.
705    #[serde(default = "default_true")]
706    pub input: bool,
707    /// Transcribe the model's audio output.
708    #[serde(default = "default_true")]
709    pub output: bool,
710}
711
712fn default_true() -> bool {
713    true
714}
715
716/// How phase instructions are steered to the model.
717#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
718#[serde(rename_all = "snake_case")]
719pub enum SteeringSpec {
720    /// Replace the system instruction on phase transitions (default).
721    InstructionUpdate,
722    /// Set the instruction once; deliver phase steering as context turns.
723    ContextInjection,
724    /// Both.
725    Hybrid,
726    /// Replace the instruction and the declared tools with `contextUpdate` at
727    /// each phase and flow-step change, so the model is offered only the
728    /// current tools (Gemini 3.8 Live; `hybrid` on other models).
729    ContextUpdate,
730}
731
732/// When batched context turns hit the wire.
733#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
734#[serde(rename_all = "snake_case")]
735pub enum ContextDeliverySpec {
736    /// Send immediately during TurnComplete (default).
737    Immediate,
738    /// Queue and flush with the next user send (voice-glitch avoidance).
739    Deferred,
740}
741
742/// Conversation-repair thresholds (unmet phase `needs`).
743#[derive(Debug, Clone, Copy, Serialize, Deserialize, schemars::JsonSchema)]
744pub struct RepairSpec {
745    /// Turns without progress before the first nudge.
746    pub nudge_after: u32,
747    /// Turns without progress before escalation.
748    pub escalate_after: u32,
749}
750
751/// Session persistence backend.
752#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
753#[serde(rename_all = "snake_case")]
754pub enum PersistenceSpec {
755    /// Filesystem snapshots under the given directory.
756    Fs {
757        /// Snapshot directory (created if missing).
758        dir: String,
759    },
760    /// In-memory (tests, ephemeral sessions).
761    Memory,
762}
763
764/// Control-plane and voice tuning — every session capability that is
765/// configuration rather than conversation, in one section. Everything here
766/// lowers to a `Live` builder setter; omitted fields keep the builder's
767/// defaults.
768#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
769pub struct RuntimeSpec {
770    /// Sampling temperature.
771    #[serde(
772        default,
773        skip_serializing_if = "Option::is_none",
774        serialize_with = "serialize_f32_exact"
775    )]
776    pub temperature: Option<f32>,
777    /// Thinking budget in tokens (Google AI only; stripped on Vertex).
778    #[serde(default, skip_serializing_if = "Option::is_none")]
779    pub thinking_budget: Option<u32>,
780    /// Receive thought summaries (requires `thinking_budget`).
781    #[serde(default, skip_serializing_if = "Option::is_none")]
782    pub include_thoughts: Option<bool>,
783    /// Input/output transcription.
784    #[serde(default, skip_serializing_if = "Option::is_none")]
785    pub transcription: Option<TranscriptionSpec>,
786    /// Let the model choose to stay silent (proactive audio).
787    #[serde(default, skip_serializing_if = "Option::is_none")]
788    pub proactive_audio: Option<bool>,
789    /// Voice-activity-detection tuning.
790    #[serde(default, skip_serializing_if = "Option::is_none")]
791    pub vad: Option<VadSpec>,
792    /// Input-audio hardening: mic chain, client VAD, interruption authority.
793    #[serde(default, skip_serializing_if = "Option::is_none")]
794    pub audio: Option<AudioSpec>,
795    /// Fire a soft turn when the model stays silent this long after VAD end.
796    #[serde(default, skip_serializing_if = "Option::is_none")]
797    pub soft_turn_timeout_ms: Option<u64>,
798    /// How phase instructions reach the model.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub steering: Option<SteeringSpec>,
801    /// When context turns hit the wire.
802    #[serde(default, skip_serializing_if = "Option::is_none")]
803    pub context_delivery: Option<ContextDeliverySpec>,
804    /// Conversation-repair thresholds.
805    #[serde(default, skip_serializing_if = "Option::is_none")]
806    pub repair: Option<RepairSpec>,
807    /// Session persistence backend.
808    #[serde(default, skip_serializing_if = "Option::is_none")]
809    pub persistence: Option<PersistenceSpec>,
810    /// Stable session id (resume across restarts; requires `persistence`).
811    #[serde(default, skip_serializing_if = "Option::is_none")]
812    pub session_id: Option<String>,
813    /// Drop audio chunks instead of applying backpressure when consumers lag.
814    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
815    pub lossy_audio: bool,
816    /// Drop transcript deltas instead of applying backpressure.
817    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
818    pub lossy_transcript: bool,
819}
820
821/// Splice a named flow fragment into the session's flow under a namespace.
822///
823/// Every step id inside the fragment becomes `{namespace}/{id}`; internal
824/// `after` edges, `done(step)` guard atoms, and `before`/`require` constraints
825/// are rewritten to match. Fragment root steps (no `after`) gain this entry's
826/// `after` dependencies, attaching the fragment into the outer DAG. Steps
827/// outside the fragment reference its steps as `{namespace}/{id}`.
828#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
829pub struct UseFragment {
830    /// Fragment name (a key in [`SessionSpec::fragments`]).
831    pub fragment: String,
832    /// Namespace prefix for the spliced step ids.
833    pub namespace: String,
834    /// Outer steps the fragment's roots depend on.
835    #[serde(default, skip_serializing_if = "Vec::is_empty")]
836    pub after: Vec<String>,
837}
838
839/// A complete Live session as one JSON document. See the module docs.
840#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
841pub struct SessionSpec {
842    /// App name (display and registry identity).
843    #[serde(default)]
844    pub name: String,
845    /// Spec version tag (freeform, e.g. "1" or "2025-08-24").
846    #[serde(default, skip_serializing_if = "String::is_empty")]
847    pub version: String,
848    /// Human-readable description.
849    #[serde(default)]
850    pub description: String,
851    /// Base system instruction.
852    #[serde(default)]
853    pub instruction: String,
854    /// Optional greeting prompt — the model speaks first on connect.
855    #[serde(default, skip_serializing_if = "Option::is_none")]
856    pub greeting: Option<String>,
857    /// Output modality. Defaults to text.
858    #[serde(default)]
859    pub modality: SpecModality,
860    /// Voice name for audio sessions (e.g. "Puck").
861    #[serde(default, skip_serializing_if = "Option::is_none")]
862    pub voice: Option<String>,
863    /// Declared tools (mock or HTTP-bound).
864    #[serde(default, skip_serializing_if = "Vec::is_empty")]
865    pub tools: Vec<ToolSpec>,
866    /// MCP toolset connection strings — the whole MCP ecosystem as this app's
867    /// tool library. Resolved at connect time.
868    #[serde(default, skip_serializing_if = "Vec::is_empty")]
869    pub mcp: Vec<String>,
870    /// Out-of-band extraction pipelines.
871    #[serde(default, skip_serializing_if = "Vec::is_empty")]
872    pub extract: Vec<ExtractSpec>,
873    /// The models the spec runs on, by role.
874    #[serde(default, skip_serializing_if = "is_default_models")]
875    pub models: ModelsSpec,
876    /// Questions a decision model (such as Jev) answers about the
877    /// conversation, by id. Guards name them with the `decided` atom, and the
878    /// runtime asks the ones the flow can act on at each decision point.
879    /// Requires [`SpecResources::decision_model`].
880    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
881    pub decisions: BTreeMap<String, DecisionSpec>,
882    /// A code tool: the model runs a short Python program whose functions
883    /// are the declared tools, each call governed like a direct call. Use it
884    /// for reads the model would otherwise add up, sort or join itself.
885    #[serde(default, skip_serializing_if = "Option::is_none")]
886    pub code: Option<CodeSpec>,
887    /// Declared state keys — the session's data dictionary.
888    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
889    pub state: BTreeMap<String, StateFieldSpec>,
890    /// Computed (derived) state variables.
891    #[serde(default, skip_serializing_if = "Vec::is_empty")]
892    pub computed: Vec<ComputedSpec>,
893    /// Durable memory: slots projected into state, `remember` effects, and
894    /// the ambient recall/manage tools. Requires a [`MemoryBinding`] in
895    /// [`SpecResources`] at apply time.
896    #[serde(default, skip_serializing_if = "Option::is_none")]
897    pub memory: Option<MemorySpec>,
898    /// Control-plane and voice tuning.
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub runtime: Option<RuntimeSpec>,
901    /// Conversation phases.
902    #[serde(default, skip_serializing_if = "Vec::is_empty")]
903    pub phases: Vec<PhaseSpec>,
904    /// Initial phase name (required when `phases` is non-empty).
905    #[serde(default, skip_serializing_if = "Option::is_none")]
906    pub initial_phase: Option<String>,
907    /// State watchers.
908    #[serde(default, skip_serializing_if = "Vec::is_empty")]
909    pub watch: Vec<WatchSpec>,
910    /// Temporal patterns (sustained / consecutive-turn conditions).
911    #[serde(default, skip_serializing_if = "Vec::is_empty")]
912    pub patterns: Vec<PatternSpec>,
913    /// Reusable flow fragments, spliced via `use_fragments`.
914    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
915    pub fragments: BTreeMap<String, Flow>,
916    /// Fragment splice directives.
917    #[serde(default, skip_serializing_if = "Vec::is_empty")]
918    pub use_fragments: Vec<UseFragment>,
919    /// The governed flow DAG (optional — a spec may be phases-only).
920    #[serde(default, skip_serializing_if = "Option::is_none")]
921    pub flow: Option<Flow>,
922    /// The conversation: stages, slots, digressions, commits, timing and
923    /// policies, compiled by the [conversation compiler](crate::conversation).
924    /// The higher-level alternative to `flow`; set one or the other. Stage
925    /// resolvers bind to the declared `tools` by name.
926    #[serde(default, skip_serializing_if = "Option::is_none")]
927    pub conversation: Option<crate::conversation::ConversationSpec>,
928    /// Reusable capabilities, each with task-private state and operations.
929    #[serde(default, skip_serializing_if = "Vec::is_empty")]
930    pub skills: Vec<SkillSpec>,
931    /// Model-free journeys through skill activation, approval and cancellation.
932    #[serde(default, skip_serializing_if = "Vec::is_empty")]
933    pub task_scenarios: Vec<TaskScenario>,
934    /// Scenarios run against `conversation` by
935    /// [`SessionSpec::run_scenarios`]: model-free, deterministic.
936    #[serde(default, skip_serializing_if = "Vec::is_empty")]
937    pub scenarios: Vec<crate::simulation::Scenario>,
938    /// Embedded conformance tests, replayed offline by
939    /// [`SessionSpec::run_tests`].
940    #[serde(default, skip_serializing_if = "Vec::is_empty")]
941    pub tests: Vec<SpecTest>,
942}
943
944/// Structured result of validating a [`SessionSpec`].
945#[derive(Debug, Clone, Serialize)]
946pub struct SpecValidation {
947    /// Whether the spec compiled cleanly.
948    pub valid: bool,
949    /// Errors (empty when valid).
950    pub errors: Vec<String>,
951    /// Non-fatal advisories.
952    pub warnings: Vec<String>,
953    /// Mermaid rendering of the effective (fragment-spliced) flow.
954    pub mermaid: String,
955    /// Every tool name the flow references.
956    pub tools: Vec<String>,
957    /// Steps in the effective flow.
958    pub steps: usize,
959}
960
961/// The seam through which a memory engine plugs into a spec-driven session.
962///
963/// The spec's `memory` section is pure data; the engine that honors it lives
964/// above this crate (`gemini-memory-rs` implements this trait over its
965/// `MemorySession`). `apply` calls [`install`](Self::install) once to wire
966/// tools/ingestion/slots, and routes every [`EffectSpec::Remember`] through
967/// [`remember`](Self::remember) for a root conversation. Skills instead bind
968/// owned services through [`task_memory`](Self::task_memory), contextual tools
969/// through [`task_tools`](Self::task_tools), and one shared task lifecycle.
970pub trait MemoryBinding: Send + Sync {
971    /// Wire the memory subsystem onto the builder per the spec's declaration.
972    fn install(&self, live: Live, memory: &MemorySpec) -> Live;
973    /// Durably remember a note (fire-and-forget; implementations may commit
974    /// asynchronously).
975    fn remember(&self, note: String);
976    /// Bind task-local projections to this session's existing memory backend.
977    /// Implementations must not capture a task's authoritative state.
978    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    /// Existing memory operations, bound to owned task invocation contexts.
985    /// The task compiler supplies their read/commit policy and ambient admission.
986    fn task_tools(&self) -> Vec<Arc<dyn ToolFunction>> {
987        Vec::new()
988    }
989    /// Install shared session teardown once, without global extractors or tools.
990    /// Serialize teardown with started effects and reject writes after sealing.
991    fn install_task_lifecycle(&self, live: Live) -> Live {
992        live
993    }
994}
995
996/// What a spec written by someone else may reach when it runs.
997///
998/// A spec can bind tools to the outside world: `mcp` entries start a local
999/// command (or connect to a URL) and an `http` binding sends a request to any
1000/// URL. That is fine for a spec you wrote and deploy. It is not fine for a
1001/// spec a browser posts to a shared server: running it would let the author
1002/// execute commands on the host or reach internal addresses. Pass such a spec
1003/// through [`SessionSpec::sandboxed`] with an allowlist the *operator*
1004/// configured.
1005///
1006/// The default allows nothing: every binding becomes a mock.
1007#[derive(Debug, Clone, Default, PartialEq, Eq)]
1008pub struct BindingAllowlist {
1009    http_prefixes: Vec<String>,
1010    mcp: Vec<String>,
1011}
1012
1013impl BindingAllowlist {
1014    /// Allow HTTP bindings whose URL template starts with `prefix`, e.g.
1015    /// `https://api.example.com/`. A prefix without a path gets a trailing
1016    /// `/`, so interpolated arguments can never change the host.
1017    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    /// Allow one `mcp` entry, matched exactly.
1028    pub fn allow_mcp(mut self, params: impl Into<String>) -> Self {
1029        self.mcp.push(params.into());
1030        self
1031    }
1032
1033    /// Whether `url` falls inside an allowed prefix. Both are parsed and
1034    /// normalized first, so `..` and `%2e%2e` segments cannot climb out of a
1035    /// path prefix, and scheme, host and port must match exactly. A template
1036    /// that interpolates into the host never matches.
1037    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
1059/// State-key prefixes the runtime itself writes (flow marking, conversation
1060/// signals), so a guard that reads one is not reading an orphan key.
1061const RUNTIME_WRITTEN: [&str; 6] = [
1062    "flow:",
1063    "session:",
1064    "verbatim:",
1065    "correction:",
1066    "repair:",
1067    "telephony:",
1068];
1069
1070/// The outcome of one scenario in [`SessionSpec::run_scenarios`].
1071#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1072pub struct ScenarioReport {
1073    /// The scenario's name.
1074    pub name: String,
1075    /// Whether every step held.
1076    pub passed: bool,
1077    /// The first step that failed, and why.
1078    #[serde(default, skip_serializing_if = "Option::is_none")]
1079    pub error: Option<String>,
1080}
1081
1082/// Tool names a [`MemoryBinding`] installs (ambient on the flow).
1083pub const MEMORY_TOOL_NAMES: [&str; 2] = ["recall_context", "manage_memory"];
1084
1085/// External resources a spec cannot carry: model handles and capability
1086/// bindings.
1087#[derive(Default, Clone)]
1088pub struct SpecResources {
1089    /// The OOB model backing `extract` entries that name no model (neither
1090    /// their own `model` nor `models.extraction`). Required when any do.
1091    pub extraction_llm: Option<Arc<dyn BaseLlm>>,
1092    /// Resolves the model names the spec writes (`models.extraction`, an
1093    /// extract entry's `model`) to models. A name it does not resolve that
1094    /// starts with `gemini` runs on [`GeminiLlm`](gemini_adk_rs::llm::GeminiLlm);
1095    /// register a prefix here to run another provider, or `""` to send every
1096    /// name to one model (a mock, in offline tests).
1097    pub models: Option<Arc<gemini_adk_rs::llm::LlmRegistry>>,
1098    /// The decision model answering the spec's `decisions`, such as
1099    /// `GatewayDecisionModel` (Jev on Vercel AI Gateway). Required when any
1100    /// are declared.
1101    pub decision_model: Option<Arc<dyn gemini_adk_rs::decision::DecisionModel>>,
1102    /// The memory engine honoring the spec's `memory` section. Required when
1103    /// that section is present.
1104    pub memory: Option<Arc<dyn MemoryBinding>>,
1105    /// Where the spec's `code` runs programs, such as a
1106    /// [`MontyPool`](gemini_adk_rs::code_mode) of worker processes. Unset:
1107    /// in this process, which cannot bound a program's memory.
1108    pub code_sandbox: Option<Arc<dyn gemini_adk_rs::code_mode::CodeSandbox>>,
1109    /// In-process implementations of declared tools, by name. A declared
1110    /// tool with an implementation calls it instead of its mock response,
1111    /// HTTP or MCP binding; its declaration (what the model sees) and its
1112    /// `set_state` stay as the spec says. Add with
1113    /// [`implement`](Self::implement).
1114    pub tools: BTreeMap<String, Arc<dyn ToolFunction>>,
1115}
1116
1117impl SpecResources {
1118    /// Bind an implementation to one skill, even when skills reuse a tool name.
1119    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    /// Implement the declared tool of the same name with `tool`.
1126    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
1132/// Serialize an `f32` by its shortest decimal form rather than its exact
1133/// binary value: an authored `0.6` must come back as `0.6`, not
1134/// `0.6000000238418579`, or every save through Flow Studio rewrites it.
1135fn 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            // `f32::to_string` is the shortest round-tripping decimal of the
1143            // f32, which parses to the same f64 a JSON author wrote.
1144            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
1155/// Resolve a named model: the host's registry first, then Gemini for
1156/// `gemini-*` names. One client per name.
1157fn 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
1185/// The model an extract entry runs on: its own `model`, then the spec's
1186/// `models.extraction`, then the host's `extraction_llm`.
1187pub(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    /// Whether some extraction (the spec's or a skill's `extract` entries)
1208    /// names no model, so it runs on the host's `extraction_llm`.
1209    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    /// Whether root or task definitions need an out-of-band extraction model.
1221    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    /// Whether root or task definitions use the contextual memory binding.
1253    pub fn requires_memory(&self) -> bool {
1254        self.memory.is_some() || self.skills.iter().any(|skill| skill.memory.is_some())
1255    }
1256
1257    /// Parse a spec from a JSON value. Accepts a full document or a *bare
1258    /// flow* (`{"steps": [...]}`), which is wrapped in a default spec.
1259    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    /// The JSON Schema of the spec document itself — for editor autocomplete
1273    /// and for validating machine-authored specs at generation time.
1274    pub fn json_schema() -> Value {
1275        serde_json::to_value(schemars::schema_for!(SessionSpec)).unwrap_or_else(|_| json!({}))
1276    }
1277
1278    /// Declared tool names (mock/HTTP; MCP names resolve at connect).
1279    pub fn tool_names(&self) -> Vec<String> {
1280        self.tools.iter().map(|t| t.name.clone()).collect()
1281    }
1282
1283    /// The flow with every `use_fragments` directive spliced in.
1284    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    /// Every state key the session declares a *writer* for: tool `set_state`
1318    /// and `save_response_as`, extraction names and promotion targets, phase
1319    /// and watcher `set` effects.
1320    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            // A computed var writes `derived:{key}`, and guards read it by
1357            // either name thanks to the `derived:` fallback.
1358            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        // A conversation's slots are filled by its extractors and resolvers.
1372        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    /// Every stage of the conversation, main flow and digressions.
1383    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    /// Resolvers for the conversation's `resolve` slots, each bound to the
1392    /// declared tool of the same name (the resolver name, or the slot).
1393    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    /// Run [`scenarios`](Self::scenarios) against the conversation, in
1424    /// order. Resolvers are stubbed: a scenario supplies their values with
1425    /// `set` steps.
1426    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    /// Every [`EffectSpec`] anywhere in the document, with a location label.
1467    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    /// Re-evaluate every computed variable in dependency order, writing
1488    /// results to `derived:{key}`. Used by the offline simulator so guards
1489    /// over computed keys latch exactly as they do live. Validation forbids
1490    /// cycles, so iterating to a fixed point terminates.
1491    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    /// Seed declared `state` defaults for keys not yet set.
1510    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    /// Validate the whole document: flow compilation (with the declared tool
1521    /// registry), fragment splicing, phase-guard restrictions, HTTP-binding
1522    /// support, and the read/write state-key diff.
1523    pub fn validate(&self) -> SpecValidation {
1524        self.validate_with_http_support(true)
1525    }
1526
1527    /// Validate for scripted offline replay, where declared tools use mock
1528    /// effects and never open HTTP or MCP connections.
1529    ///
1530    /// Checks the original document, including conflicting tool bindings.
1531    /// Only the requirement to compile HTTP transport support is omitted.
1532    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                        // The session reports unpinned extraction once, with
1605                        // its own `models.extraction` taken into account.
1606                        .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        // Fragment namespace validation: must be non-empty to create valid step ids.
1615        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        // Check for duplicate phase names
1661        {
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        // Computed variables: unique keys, no dependency cycles (Kahn over the
1720        // computed subset; a bare read and a `derived:` read are the same
1721        // dependency).
1722        {
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                    // Every dependent is a computed key, and every computed key
1756                    // has an entry; an absent one would only leave `visited`
1757                    // short and be reported as a cycle below.
1758                    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        // Effects: `remember` needs the memory section; memory slots must not
1781        // target the read-only `derived:` scope.
1782        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        // Declared state dictionary: defaults must match their declared type;
1802        // once a dictionary exists, undeclared keys are worth flagging.
1803        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        // Computed inputs: like guard reads, a dependency nothing writes can
1830        // never produce a value.
1831        {
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        // Runtime coherence.
1849        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        // Flow compilation, with declared tools as the registry. MCP tool
1917        // names are unknown until connect, so their presence downgrades the
1918        // unknown-tool check to a warning-free plain compile.
1919        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                    // The memory binding installs its tools at connect; the
1933                    // flow may reference or gate them.
1934                    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            // Read/write state-key diff — the guard-key analogue of the
1964            // unknown-tool check.
1965            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                // `{name}:result` keys are written by on_enter orchestration.
1970                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            // Digressions are not part of the lowered main flow; the tools
1989            // their stages admit or commit are referenced too.
1990            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        // Extraction models.
2022        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        // Decisions.
2046        let (decision_errors, decision_warnings) = self.decision_problems();
2047        errors.extend(decision_errors);
2048        warnings.extend(decision_warnings);
2049
2050        // Code mode.
2051        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    /// Build the dispatcher of declared tools bound to `state`.
2066    pub fn build_dispatcher(&self, state: &State) -> ToolDispatcher {
2067        self.build_dispatcher_with(state, &SpecResources::default())
2068    }
2069
2070    /// Build the dispatcher of declared tools bound to `state`, calling the
2071    /// in-process implementations in `resources` where it has them. Tools
2072    /// bound to the same MCP server share one connection.
2073    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    /// Every declared tool, bound to its call: the in-process implementation
2086    /// in `resources`, else its MCP server, else its HTTP binding or mock.
2087    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    /// Apply the mock semantics of a declared tool to `state` (its
2112    /// `set_state` writes). Used by the offline simulator.
2113    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    /// Run the embedded test suite offline (no model, no network) — scripted
2122    /// events replayed through the real [`FlowStack`](gemini_adk_rs::flow::FlowStack).
2123    /// Includes installed skill workflow tests, named `skill/test`.
2124    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    /// A copy of this spec that reaches only what `allow` permits, and one
2136    /// note per binding it disabled.
2137    ///
2138    /// `mcp` entries not in the allowlist are removed. A tool whose `http`
2139    /// binding is not allowed becomes a mock: it returns its canned
2140    /// `response` and still writes `set_state`, so the flow behaves the same
2141    /// way offline. Use this before [`apply`](Self::apply) on any spec you did
2142    /// not write, such as one posted by a browser.
2143    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                // Arguments are interpolated and servers redirect at call
2175                // time, so the request is checked again then.
2176                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    /// Configure a [`Live`] builder from this spec.
2189    ///
2190    /// `state` is the session state the declared tools bind to — pass the
2191    /// same one via `.state` (this method does). Returns an error when
2192    /// the spec fails validation or requires a resource `resources` lacks.
2193    /// Everything code-only (callbacks, custom guards, middleware) is added on
2194    /// the returned builder afterwards.
2195    ///
2196    /// Tool bindings run as written. For a spec you did not write, call
2197    /// [`sandboxed`](Self::sandboxed) first.
2198    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        // Seed declared defaults before anything reads state.
2247        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        // Tools: declared (mock/HTTP) via the dispatcher, MCP merged on top.
2276        // A conversation's resolvers call the same bound tools.
2277        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        // Governance: a conversation compiles to a governed stack with its
2290        // extractors, timing and policies; a bare flow is governed as is.
2291        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        // Computed (derived) state variables — dependencies inferred from the
2306        // expression, so the registry's topological ordering holds.
2307        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        // Memory: install through the binding (tools, ingestion, slots).
2315        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        // Background tools (async function calling).
2321        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        // Control-plane and voice tuning.
2335        if let Some(runtime) = &self.runtime {
2336            live = apply_runtime(live, runtime);
2337        }
2338
2339        // Extraction, each entry on its model.
2340        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        // Phases.
2356        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        // Temporal patterns.
2400        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        // Watchers.
2425        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
2455/// Shared extractor lowering for session and task-owned services. `models`
2456/// is the session's, for the thinking budget an entry does not set.
2457fn 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
2472/// Execute a list of closed effects — the one executor behind phase
2473/// `on_enter`, watcher, and pattern actions, so every surface honors the
2474/// vocabulary identically.
2475async 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
2507/// Lower the turn-commit tuning knobs onto the Live builder. A knob left
2508/// unset keeps the default from
2509/// [`TurnCommitConfig::responsive()`](gemini_adk_rs::live::TurnCommitConfig::responsive).
2510fn 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
2524/// Lower the `runtime` section onto the builder.
2525fn 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        // Turn-commit tuning knobs integration seam: if either field is set,
2570        // the Live builder's turn_commit(...) method will wire them through.
2571        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
2618/// How a declared tool's call is carried out.
2619enum ToolCall {
2620    /// Its `http` binding, or its canned response.
2621    Declared,
2622    /// An in-process implementation.
2623    Code(Arc<dyn ToolFunction>),
2624    /// The tool of the same name on an MCP server.
2625    Mcp(Arc<gemini_adk_rs::tools::mcp::McpSessionManager>),
2626}
2627
2628/// The value of an MCP `tools/call` result: its structured content, else
2629/// its single text part parsed as JSON, else the text itself.
2630fn 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
2647/// Build one declared tool, carrying out calls with `call`. Whatever carries
2648/// it out, the declaration and the state effects are the spec's.
2649fn 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
2701/// Interpolate `{args.field}` and `{state.key}` templates in a string.
2702fn 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/// Walk a JSON value, interpolating every string.
2715#[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
2785/// Splice `fragment` into `flow` under the directive's namespace.
2786fn 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
2905/// Rewrite `done(step)` atoms that reference fragment-internal steps.
2906fn 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
2926/// Whether a guard contains `called_ok`/`done` atoms, which need a flow
2927/// marking and therefore cannot back phase transitions.
2928fn 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
2943/// Resolve a voice name to the `Voice` enum: a preset by name, `Puck` when
2944/// absent, any other name as a custom voice.
2945pub 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); // serde default
2978        let config = audio.client_vad.as_ref().unwrap().to_config();
2979        assert_eq!(config.start_threshold_db, 21.0); // preset
2980        assert_eq!(config.hangover_frames, 12); // override wins
2981        assert_eq!(audio.authority, Some(AuthoritySpec::Client));
2982        // Round-trips through JSON unchanged.
2983        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        // Round-trips through JSON unchanged.
3045        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        // Warn on eot_hold_ms > 1600
3055        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        // Warn on min_interruption_ms > 2000
3074        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        // Typo in the guard key relative to the tool's write.
3144        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        // Internal done() atom rewritten to the namespaced id.
3200        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        // Empty namespace should be a validation error
3235        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        // Test that explicitly setting background: false round-trips correctly
3290        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        // After serialization
3301        let serialized = serde_json::to_value(&spec).unwrap();
3302        let tools = serialized["tools"].as_array().unwrap();
3303
3304        // background: false is skipped in serialization (optimization), but
3305        // when deserialized, missing field defaults to false ✓
3306        assert!(
3307            tools[0].get("background").is_none(),
3308            "background: false is optimized away"
3309        );
3310
3311        // background: true is serialized
3312        assert_eq!(tools[1].get("background"), Some(&json!(true)));
3313
3314        // Round-trip test
3315        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        // Test that promotion without explicit "to" uses the field name as target
3323        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    /// The did-you-mean hint's edit distance counts characters, not bytes.
3388    #[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        // A prefix without a path cannot be stretched to another host.
3696        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        // Dot segments are resolved before a path prefix is checked.
3703        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        // A local server that redirects /v2/hop to /admin and answers
3716        // anything else with its path.
3717        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        // An argument cannot climb out of the prefix...
3755        let climbed = dispatcher
3756            .call_function("get", json!({ "path": "../admin" }))
3757            .await;
3758        assert!(climbed.is_err(), "{climbed:?}");
3759        // ...and neither can a redirect.
3760        let redirected = dispatcher
3761            .call_function("get", json!({ "path": "hop" }))
3762            .await;
3763        assert!(redirected.is_err(), "{redirected:?}");
3764
3765        // The same spec, not sandboxed, follows the redirect as written.
3766        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    /// The repo's booking conversation, as one spec with its tools and
3775    /// scenarios.
3776    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        // Collected slots are written by the conversation's extractors, so
3828        // only the genuinely unwritten key is reported.
3829        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        // Conversation and flow are alternatives.
3840        let mut both = spec.clone();
3841        both.flow = Some(Flow::default());
3842        assert!(!both.validate().valid);
3843
3844        // A resolver must be a declared tool.
3845        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        // The spec's state effects still apply.
3914        assert_eq!(state.get::<bool>("booked"), Some(true));
3915        assert_eq!(
3916            state.get::<Value>("booking").unwrap()["confirmation"],
3917            "REAL-7"
3918        );
3919        // And the model still sees the spec's declaration.
3920        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        // An implementation for a tool the spec does not declare is refused.
3930        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        // A minimal stdio MCP server: answers initialize and tools/call.
3943        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        // Both bindings on one tool is a validation error.
3971        let both = booking_tool(json!({
3972            "mcp": "x",
3973            "http": { "url": "https://api.example.com/book" }
3974        }));
3975        assert!(!both.validate().valid);
3976
3977        // A sandbox without that entry allowed turns the tool into its mock.
3978        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        // Named models need no extraction_llm.
4043        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        // No extraction LLM provided → apply must refuse (extraction declared).
4116        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        // Without the extraction entries it applies clean.
4123        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}