Skip to main content

agy_bridge/config/
agent.rs

1//! Agent configuration, system instructions, and local agent config.
2
3use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6use typed_builder::TypedBuilder;
7
8use super::{
9    DEFAULT_MODEL, capabilities::CapabilitiesConfig, mcp::McpServer, models::GeminiConfig,
10};
11use crate::{
12    hooks::HookEntry, policies::PolicyRule, tools::ToolDefinition, triggers::TriggerEntry,
13};
14
15/// A section within a system instruction, with a label and body text.
16#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
17pub struct SystemInstructionSection {
18    /// The content of the section.
19    pub content: String,
20    /// The title/label for this section.
21    #[serde(default = "default_section_title")]
22    pub title: String,
23}
24
25fn default_section_title() -> String {
26    "user_system_instructions".to_owned()
27}
28
29fn default_model_name() -> String {
30    DEFAULT_MODEL.to_owned()
31}
32
33/// System instruction configuration, mirroring the Python SDK's union type.
34///
35/// Uses internal tagging via `#[serde(untagged)]` so each variant is
36/// distinguishable by its `"mode"` field in JSON (e.g. `{"mode": "Custom", "text": "..."}`).
37#[non_exhaustive]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum SystemInstructions {
41    /// Completely replace the default system instructions (advanced usage).
42    Custom(String),
43    /// Override identity and/or append sections to the defaults (recommended).
44    Templated {
45        /// Optional identity string that replaces the agent's default persona.
46        #[serde(default)]
47        identity: Option<String>,
48        /// Sections appended to the default system instructions.
49        #[serde(default)]
50        sections: Vec<SystemInstructionSection>,
51    },
52}
53
54impl SystemInstructions {
55    /// Create custom system instructions from a plain text string.
56    #[must_use]
57    pub fn custom(text: impl Into<String>) -> Self {
58        Self::Custom(text.into())
59    }
60}
61
62impl From<&str> for SystemInstructions {
63    fn from(s: &str) -> Self {
64        Self::custom(s)
65    }
66}
67
68impl From<String> for SystemInstructions {
69    fn from(s: String) -> Self {
70        Self::custom(s)
71    }
72}
73
74// ─── JSON Schema newtype ──────────────────────────────────────────────────────────────────
75
76/// A JSON Schema definition for structured output.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(transparent)]
79pub struct JsonSchema(serde_json::Value);
80
81impl JsonSchema {
82    #[must_use]
83    /// Wrap a raw `serde_json::Value` as a `JsonSchema`.
84    pub const fn new(value: serde_json::Value) -> Self {
85        Self(value)
86    }
87
88    #[must_use]
89    /// Return a reference to the inner JSON value.
90    pub const fn as_value(&self) -> &serde_json::Value {
91        &self.0
92    }
93
94    /// Validate that the schema is structurally sound.
95    ///
96    /// Currently checks that the top-level value is a JSON object (i.e.
97    /// `serde_json::Value::Object`), which is the minimum requirement for a
98    /// valid JSON Schema.
99    ///
100    /// # Errors
101    ///
102    /// Returns a static error message if the schema is not an object.
103    pub fn validate(&self) -> Result<(), &'static str> {
104        if self.0.is_object() {
105            Ok(())
106        } else {
107            Err("JSON Schema must be a JSON object at the top level")
108        }
109    }
110}
111
112// ─── AgentConfig ─────────────────────────────────────────────────────────────
113
114/// Full configuration for creating an agent.
115///
116/// Covers model selection, system instructions, capabilities, tools,
117/// policies, hooks, MCP servers, structured output, and Gemini backend
118/// settings. All fields have sensible defaults.
119///
120/// # Construction patterns
121///
122/// `AgentConfig` deliberately supports **two** construction paths:
123///
124/// 1. **[`TypedBuilder`]** — ergonomic chained construction with `impl
125///    IntoIterator` setters for collection fields. Preferred for
126///    programmatic use:
127///    ```
128///    # use agy_bridge::config::AgentConfig;
129///    let config = AgentConfig::builder()
130///        .model("gemini-3.5-flash")
131///        .build();
132///    ```
133///
134/// 2. **Struct literal with `..Default::default()`** — convenient for
135///    deserialization (`serde`), config files, and framework code that
136///    already has fully-formed values:
137///    ```
138///    # use agy_bridge::config::AgentConfig;
139///    let config = AgentConfig {
140///        model: "gemini-3.5-flash".into(),
141///        ..AgentConfig::default()
142///    };
143///    ```
144///
145/// Both paths are supported intentionally. The builder provides ergonomic
146/// setters (e.g. accepting `impl IntoIterator` for collection fields),
147/// while struct literals enable direct field access for serialization
148/// roundtrips and downstream framework integration.
149#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
150#[builder(field_defaults(default))]
151pub struct AgentConfig {
152    /// The model name (e.g. `"gemini-3.5-flash"`).
153    #[serde(default = "default_model_name")]
154    #[builder(default = DEFAULT_MODEL.to_owned(), setter(into))]
155    pub model: String,
156    /// API key. Falls back to `GEMINI_API_KEY` env var if `None`.
157    #[serde(default)]
158    #[builder(setter(into, strip_option))]
159    pub api_key: Option<String>,
160    /// Optional system instructions (custom text or templated sections).
161    #[builder(setter(into, strip_option))]
162    pub system_instructions: Option<SystemInstructions>,
163    #[serde(default)]
164    /// Agent capability toggles (tool lists, subagents, compaction).
165    #[builder(setter(strip_option))]
166    pub capabilities: Option<CapabilitiesConfig>,
167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
168    /// Workspace directories the agent can access.
169    ///
170    /// When empty (the default), the Python SDK's own default of
171    /// `[os.getcwd()]` applies. Set explicitly to override.
172    #[builder(setter(transform = |v: impl IntoIterator<Item = impl Into<PathBuf>>| v.into_iter().map(Into::into).collect()))]
173    pub workspaces: Vec<PathBuf>,
174    #[serde(default, skip_serializing_if = "Vec::is_empty")]
175    /// Custom tool definitions exposed to the agent.
176    #[builder(setter(transform = |v: impl IntoIterator<Item = impl Into<ToolDefinition>>| v.into_iter().map(Into::into).collect()))]
177    pub tools: Vec<ToolDefinition>,
178    #[serde(default = "default_policies")]
179    /// Policy rules evaluated before each tool call.
180    #[builder(default = default_policies(), setter(transform = |v: impl IntoIterator<Item = impl Into<PolicyRule>>| v.into_iter().map(Into::into).collect()))]
181    pub policies: Vec<PolicyRule>,
182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
183    /// Event-driven triggers attached to this agent.
184    #[builder(setter(transform = |v: impl IntoIterator<Item = impl Into<TriggerEntry>>| v.into_iter().map(Into::into).collect()))]
185    pub triggers: Vec<TriggerEntry>,
186    #[serde(default, skip_serializing_if = "Vec::is_empty")]
187    /// Lifecycle hooks (pre-turn, post-turn, pre-tool, etc.).
188    #[builder(setter(transform = |v: impl IntoIterator<Item = impl Into<HookEntry>>| v.into_iter().map(Into::into).collect()))]
189    pub hooks: Vec<HookEntry>,
190    #[serde(
191        default,
192        skip_serializing_if = "Vec::is_empty",
193        rename = "skills_paths"
194    )]
195    /// Paths to skill instruction files loaded into the agent.
196    ///
197    /// Serializes as `"skills_paths"` to match the Python SDK field name.
198    #[builder(setter(transform = |v: impl IntoIterator<Item = impl Into<PathBuf>>| v.into_iter().map(Into::into).collect()))]
199    pub skills: Vec<PathBuf>,
200
201    /// MCP server configurations.
202    #[serde(default, skip_serializing_if = "Vec::is_empty")]
203    #[builder(setter(transform = |v: impl IntoIterator<Item = impl Into<McpServer>>| v.into_iter().map(Into::into).collect()))]
204    pub mcp_servers: Vec<McpServer>,
205    /// Pre-existing conversation ID to resume.
206    #[serde(default)]
207    #[builder(setter(into, strip_option))]
208    pub conversation_id: Option<String>,
209    /// Directory where conversation state is saved.
210    #[serde(default)]
211    #[builder(setter(into, strip_option))]
212    pub save_dir: Option<PathBuf>,
213    /// Application data directory.
214    #[serde(default)]
215    #[builder(setter(into, strip_option))]
216    pub app_data_dir: Option<PathBuf>,
217    /// Optional JSON schema for structured responses.
218    #[serde(default)]
219    #[builder(setter(strip_option))]
220    pub response_schema: Option<JsonSchema>,
221    /// Gemini model backend configuration.
222    ///
223    /// Controls per-model API keys, model selection per capability,
224    /// and generation parameters such as `thinking_level`.
225    ///
226    /// Serializes as `"gemini_config"` to match the Python SDK field name.
227    #[serde(default, rename = "gemini_config")]
228    #[builder(setter(strip_option))]
229    pub gemini: Option<GeminiConfig>,
230    /// Optional initial conversation history to inject after agent creation.
231    ///
232    /// When set, these messages are inserted into the SDK's internal
233    /// `_history` list before the first chat turn, enabling warm-start
234    /// scenarios such as safety recovery (re-creating an agent with
235    /// curated prior context).
236    ///
237    /// Serialized as `"initial_history"` and consumed by the Python init
238    /// script. Skipped from serialization when empty.
239    #[serde(default, skip_serializing_if = "Vec::is_empty")]
240    #[builder(default, setter(transform = |v: impl IntoIterator<Item = impl Into<crate::types::ConversationMessage>>| v.into_iter().map(Into::into).collect()))]
241    pub initial_history: Vec<crate::types::ConversationMessage>,
242}
243
244impl Default for AgentConfig {
245    fn default() -> Self {
246        Self::builder().build()
247    }
248}
249
250impl AgentConfig {
251    /// Resolve the effective API key using the same priority chain as the
252    /// Python SDK's `LocalAgentConfig` → `_build_harness_config`:
253    ///
254    /// 1. Per-model key (`gemini.models.default.api_key`)
255    /// 2. Shared `GeminiConfig` key (`gemini.api_key`)
256    /// 3. Top-level shorthand (`api_key`)
257    /// 4. `$GEMINI_API_KEY` environment variable
258    #[must_use]
259    pub fn effective_api_key(&self) -> Option<String> {
260        self.gemini
261            .as_ref()
262            .and_then(|g| g.models.default.api_key.clone())
263            .or_else(|| self.gemini.as_ref().and_then(|g| g.api_key.clone()))
264            .or_else(|| self.api_key.clone())
265            // NOLINT: .ok() is intentional — env var not set returns None, which is the expected fallback
266            .or_else(|| std::env::var("GEMINI_API_KEY").ok())
267    }
268
269    /// Returns the names of all explicitly registered custom tools.
270    /// To get the full list of tools including built-ins, combine this
271    /// with `capabilities.enabled_tools` or examine `tools` + default semantics.
272    #[must_use]
273    pub fn custom_tool_names(&self) -> Vec<String> {
274        self.tools.iter().map(|t| t.name.clone()).collect()
275    }
276}
277
278// ─── LocalAgentConfig ────────────────────────────────────────────────────────
279
280/// Configuration for a local (on-device) agent, mirroring the Python SDK's
281/// `LocalAgentConfig`.
282///
283/// Wraps the standard [`AgentConfig`] via `#[serde(flatten)]`. The Python SDK's
284/// `LocalAgentConfig` extends the base `AgentConfig` with override defaults
285/// (e.g. `policies = confirm_run_command()`, `workspaces = [cwd]`), which
286/// our `AgentConfig` already matches.
287#[derive(Debug, Clone, Serialize, Deserialize, Default)]
288pub struct LocalAgentConfig {
289    /// The base agent configuration.
290    #[serde(flatten)]
291    pub agent: AgentConfig,
292}
293
294impl LocalAgentConfig {
295    /// Create a new `LocalAgentConfig` wrapping the given agent configuration.
296    #[must_use]
297    pub const fn new(agent: AgentConfig) -> Self {
298        Self { agent }
299    }
300}
301
302impl From<AgentConfig> for LocalAgentConfig {
303    fn from(agent: AgentConfig) -> Self {
304        Self::new(agent)
305    }
306}
307
308/// Matches the Python SDK's `LocalAgentConfig` default: block `run_command`,
309/// allow all other tools.
310fn default_policies() -> Vec<PolicyRule> {
311    vec![
312        PolicyRule::Deny("run_command".to_string()),
313        PolicyRule::AllowAll,
314    ]
315}
316
317#[cfg(test)]
318mod tests {
319    use pyo3::types::PyAnyMethods;
320
321    use super::{
322        super::{
323            DEFAULT_IMAGE_GENERATION_MODEL,
324            capabilities::BuiltinTools,
325            models::{
326                GenerationConfig, ModelConfig, ModelEntry, ThinkingLevel, default_image_model_entry,
327            },
328        },
329        *,
330    };
331
332    #[derive(schemars::JsonSchema)]
333    struct CustomToolParams {}
334
335    #[test]
336    fn test_roundtrip_serialization() {
337        let config = AgentConfig {
338            system_instructions: Some(SystemInstructions::Custom("Be helpful".to_string())),
339            capabilities: Some(CapabilitiesConfig {
340                enable_subagents: true,
341                enabled_tools: Some(vec![BuiltinTools::ListDir]),
342                compaction_threshold: Some(4000),
343                ..CapabilitiesConfig::default()
344            }),
345            workspaces: vec![PathBuf::from("/tmp")],
346            ..AgentConfig::default()
347        };
348
349        let json = serde_json::to_string(&config).unwrap();
350        let parsed: AgentConfig = serde_json::from_str(&json).unwrap();
351        assert_eq!(parsed.workspaces.len(), 1);
352        assert_eq!(
353            parsed.capabilities.unwrap().enabled_tools.unwrap()[0],
354            BuiltinTools::ListDir
355        );
356    }
357
358    #[test]
359    fn agent_config_builder_with_gemini() {
360        let gemini = GeminiConfig {
361            api_key: Some("test-key".to_string()),
362            base_url: None,
363            models: ModelConfig::default(),
364        };
365        let config = AgentConfig::builder().gemini(gemini).build();
366        let gemini_cfg = config.gemini.expect("gemini should be Some");
367        assert_eq!(gemini_cfg.api_key.as_deref(), Some("test-key"));
368        assert_eq!(gemini_cfg.models.default.name, DEFAULT_MODEL);
369    }
370
371    #[test]
372    fn agent_config_builder_gemini_with_thinking_level() {
373        let gemini = GeminiConfig {
374            api_key: None,
375            base_url: None,
376            models: ModelConfig {
377                default: ModelEntry {
378                    name: "gemini-3.5-flash".to_string(),
379                    api_key: None,
380                    generation: GenerationConfig {
381                        thinking_level: Some(ThinkingLevel::High),
382                    },
383                },
384                image_generation: default_image_model_entry(),
385            },
386        };
387        let config = AgentConfig::builder().gemini(gemini).build();
388        let gemini_cfg = config.gemini.expect("gemini should be Some");
389        assert_eq!(
390            gemini_cfg.models.default.generation.thinking_level,
391            Some(ThinkingLevel::High)
392        );
393        assert_eq!(gemini_cfg.models.default.name, "gemini-3.5-flash");
394    }
395
396    #[test]
397    fn agent_config_gemini_none_by_default() {
398        let config = AgentConfig::default();
399        assert!(config.gemini.is_none());
400    }
401
402    #[test]
403    fn agent_config_gemini_serde_roundtrip() {
404        let config = AgentConfig {
405            gemini: Some(GeminiConfig {
406                api_key: Some("roundtrip-key".to_string()),
407                base_url: None,
408                models: ModelConfig {
409                    default: ModelEntry {
410                        name: "gemini-3.5-flash".to_string(),
411                        api_key: Some("model-key".to_string()),
412                        generation: GenerationConfig {
413                            thinking_level: Some(ThinkingLevel::Medium),
414                        },
415                    },
416                    image_generation: default_image_model_entry(),
417                },
418            }),
419            ..AgentConfig::default()
420        };
421        let json = serde_json::to_string(&config).unwrap();
422        let parsed: AgentConfig = serde_json::from_str(&json).unwrap();
423        let gemini_cfg = parsed.gemini.expect("gemini should survive roundtrip");
424        assert_eq!(gemini_cfg.api_key.as_deref(), Some("roundtrip-key"));
425        assert_eq!(gemini_cfg.models.default.name, "gemini-3.5-flash");
426        assert_eq!(
427            gemini_cfg.models.default.api_key.as_deref(),
428            Some("model-key")
429        );
430        assert_eq!(
431            gemini_cfg.models.default.generation.thinking_level,
432            Some(ThinkingLevel::Medium)
433        );
434    }
435
436    #[test]
437    fn system_instructions_custom_serde() {
438        let instr = SystemInstructions::Custom("Be a helpful assistant".to_string());
439        let json = serde_json::to_string(&instr).unwrap();
440        let parsed: SystemInstructions = serde_json::from_str(&json).unwrap();
441        match parsed {
442            SystemInstructions::Custom(text) => assert_eq!(text, "Be a helpful assistant"),
443            SystemInstructions::Templated { .. } => {
444                panic!("Expected Custom, got Templated")
445            }
446        }
447    }
448
449    #[test]
450    fn system_instructions_templated_serde() {
451        let instr = SystemInstructions::Templated {
452            identity: Some("a security analyst".to_string()),
453            sections: vec![SystemInstructionSection {
454                content: "Always check permissions".to_string(),
455                title: "security".to_string(),
456            }],
457        };
458        let json = serde_json::to_string(&instr).unwrap();
459        let parsed: SystemInstructions = serde_json::from_str(&json).unwrap();
460        match parsed {
461            SystemInstructions::Templated { identity, sections } => {
462                assert_eq!(identity.as_deref(), Some("a security analyst"));
463                assert_eq!(sections.len(), 1);
464                assert_eq!(sections[0].content, "Always check permissions");
465            }
466            SystemInstructions::Custom(_) => {
467                panic!("Expected Templated, got Custom")
468            }
469        }
470    }
471
472    #[test]
473    fn agent_config_fully_populated_serde() {
474        let config = AgentConfig {
475            system_instructions: Some(SystemInstructions::Templated {
476                identity: Some("test-identity".to_string()),
477                sections: vec![],
478            }),
479            capabilities: Some(CapabilitiesConfig {
480                enable_subagents: true,
481                disabled_tools: Some(vec![BuiltinTools::RunCommand]),
482                compaction_threshold: Some(1000),
483                ..CapabilitiesConfig::default()
484            }),
485            workspaces: vec![PathBuf::from("/a"), PathBuf::from("/b")],
486            tools: vec![crate::tools::ToolDefinition {
487                name: "custom_tool".to_owned(),
488                description: "A custom tool".to_owned(),
489                parameter_schema: serde_json::to_value(schemars::schema_for!(CustomToolParams))
490                    .unwrap(),
491            }],
492            policies: vec![PolicyRule::DenyAll],
493            triggers: vec![TriggerEntry {
494                name: "poll".to_owned(),
495                config: crate::triggers::TriggerConfig::every_secs(30),
496                message_template: "time to poll".to_owned(),
497            }],
498            hooks: vec![HookEntry {
499                name: "pre_gate".to_owned(),
500                point: crate::hooks::HookPoint::PreTurn,
501                callback_id: "cb_pre".to_owned(),
502            }],
503            skills: vec![PathBuf::from("/skills/foo")],
504            ..AgentConfig::default()
505        };
506        let json = serde_json::to_string(&config).unwrap();
507        let parsed: AgentConfig = serde_json::from_str(&json).unwrap();
508        assert_eq!(parsed.workspaces.len(), 2);
509        assert_eq!(parsed.tools.len(), 1);
510        assert_eq!(parsed.policies.len(), 1);
511        assert_eq!(parsed.triggers.len(), 1);
512        assert_eq!(parsed.hooks.len(), 1);
513        assert_eq!(parsed.skills.len(), 1);
514    }
515
516    #[test]
517    fn agent_config_empty_defaults_serde() {
518        let json = r#"{"system_instructions":null}"#;
519        let parsed: AgentConfig = serde_json::from_str(json).unwrap();
520        assert!(parsed.system_instructions.is_none());
521        assert!(parsed.capabilities.is_none());
522        assert!(parsed.workspaces.is_empty());
523        assert!(parsed.tools.is_empty());
524        assert_eq!(
525            parsed.policies,
526            vec![
527                PolicyRule::Deny("run_command".to_string()),
528                PolicyRule::AllowAll,
529            ]
530        );
531        assert!(parsed.triggers.is_empty());
532        assert!(parsed.hooks.is_empty());
533        assert!(parsed.skills.is_empty());
534
535        assert!(parsed.gemini.is_none());
536    }
537
538    #[test]
539    fn agent_config_all_optional_fields_roundtrip() {
540        let config = AgentConfig {
541            workspaces: vec![PathBuf::from("/ws")],
542            skills: vec![PathBuf::from("/skills/test")],
543
544            conversation_id: Some("conv-123".to_string()),
545            save_dir: Some(PathBuf::from("/save")),
546            app_data_dir: Some(PathBuf::from("/app")),
547            response_schema: Some(JsonSchema::new(serde_json::json!({"type": "object"}))),
548            ..AgentConfig::default()
549        };
550        let json = serde_json::to_string(&config).unwrap();
551        let parsed: AgentConfig = serde_json::from_str(&json).unwrap();
552        assert_eq!(parsed.workspaces.len(), 1);
553        assert_eq!(parsed.conversation_id.as_deref(), Some("conv-123"));
554        assert_eq!(parsed.save_dir.as_ref().unwrap(), &PathBuf::from("/save"));
555        assert!(parsed.response_schema.is_some());
556    }
557
558    #[test]
559    fn agent_config_custom_tools_and_builtin_tools_coexist() {
560        // Audit 3: Verify that an AgentConfig can carry both custom tool
561        // definitions (for the ToolRegistry) AND SDK built-in tools
562        // (via CapabilitiesConfig.enabled_tools) at the same time.
563        let custom_tool = crate::tools::ToolDefinition {
564            name: "my_custom_tool".to_owned(),
565            description: "Does something custom".to_owned(),
566            parameter_schema: serde_json::json!({"type": "object", "properties": {}}),
567        };
568        let config = AgentConfig {
569            tools: vec![custom_tool],
570            capabilities: Some(CapabilitiesConfig {
571                enabled_tools: Some(vec![BuiltinTools::ViewFile, BuiltinTools::RunCommand]),
572                ..CapabilitiesConfig::default()
573            }),
574            ..AgentConfig::default()
575        };
576
577        // Serialize and deserialize to prove the combined config survives a roundtrip.
578        let json = serde_json::to_string(&config).unwrap();
579        let parsed: AgentConfig = serde_json::from_str(&json).unwrap();
580
581        // Custom tools are preserved.
582        assert_eq!(parsed.tools.len(), 1);
583        assert_eq!(parsed.tools[0].name, "my_custom_tool");
584
585        // Built-in tool selection is preserved.
586        let caps = parsed.capabilities.as_ref().unwrap();
587        let enabled = caps.enabled_tools.as_ref().unwrap();
588        assert_eq!(enabled.len(), 2);
589        assert!(enabled.contains(&BuiltinTools::ViewFile));
590        assert!(enabled.contains(&BuiltinTools::RunCommand));
591
592        // Validate the config is internally consistent.
593        assert!(caps.validate().is_ok());
594    }
595
596    #[test]
597    fn agent_config_custom_tools_only_no_builtins() {
598        // Verify custom_tools_only() + custom tools is valid.
599        let config = AgentConfig {
600            tools: vec![crate::tools::ToolDefinition {
601                name: "fetch_data".to_owned(),
602                description: "Fetches data".to_owned(),
603                parameter_schema: serde_json::json!({"type": "object"}),
604            }],
605            capabilities: Some(CapabilitiesConfig::custom_tools_only()),
606            ..AgentConfig::default()
607        };
608
609        let caps = config.capabilities.as_ref().unwrap();
610        assert!(caps.enabled_tools.as_ref().unwrap().is_empty());
611        assert!(caps.validate().is_ok());
612        assert_eq!(config.tools.len(), 1);
613    }
614
615    // ── LocalAgentConfig tests ───────────────────────────────────────
616
617    #[test]
618    fn local_agent_config_default() {
619        let config = LocalAgentConfig::default();
620        assert_eq!(config.agent.model, DEFAULT_MODEL);
621    }
622
623    #[test]
624    fn local_agent_config_from_agent_config() {
625        let agent_cfg = AgentConfig {
626            model: "gemini-3.5-flash".to_string(),
627            ..AgentConfig::default()
628        };
629        let local: LocalAgentConfig = agent_cfg.into();
630        assert_eq!(local.agent.model, "gemini-3.5-flash");
631    }
632
633    #[test]
634    fn local_agent_config_serde_roundtrip() {
635        let config = LocalAgentConfig::new(AgentConfig::default());
636        let json = serde_json::to_string(&config).unwrap();
637        let parsed: LocalAgentConfig = serde_json::from_str(&json).unwrap();
638        assert_eq!(parsed.agent.model, DEFAULT_MODEL);
639    }
640
641    // ── SDK field name alignment tests ────────────────────────────────
642    //
643    // Verify that serde serializes field names to match the Python SDK's
644    // expected JSON keys.
645
646    #[test]
647    fn skills_serializes_as_skills_paths() {
648        let config = AgentConfig::builder()
649            .skills(vec![PathBuf::from("/skill/a.md")])
650            .build();
651        let json = serde_json::to_string(&config).unwrap();
652        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
653        assert!(
654            v.get("skills_paths").is_some(),
655            "Expected JSON key 'skills_paths', got: {json}"
656        );
657        assert!(
658            v.get("skills").is_none(),
659            "Should not have 'skills' key in JSON"
660        );
661    }
662
663    #[test]
664    fn skills_paths_deserializes_to_skills_field() {
665        let json = r#"{"skills_paths": ["/skill/a.md"]}"#;
666        let config: AgentConfig = serde_json::from_str(json).unwrap();
667        assert_eq!(config.skills.len(), 1);
668        assert_eq!(config.skills[0], PathBuf::from("/skill/a.md"));
669    }
670
671    #[test]
672    fn gemini_serializes_as_gemini_config() {
673        let config = AgentConfig::builder()
674            .gemini(super::super::GeminiConfig::default())
675            .build();
676        let json = serde_json::to_string(&config).unwrap();
677        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
678        assert!(
679            v.get("gemini_config").is_some(),
680            "Expected JSON key 'gemini_config', got: {json}"
681        );
682        assert!(
683            v.get("gemini").is_none(),
684            "Should not have 'gemini' key in JSON"
685        );
686    }
687
688    #[test]
689    fn gemini_config_deserializes_to_gemini_field() {
690        let json = r#"{"gemini_config": {"api_key": "test-key"}}"#;
691        let config: AgentConfig = serde_json::from_str(json).unwrap();
692        assert_eq!(
693            config.gemini.as_ref().unwrap().api_key.as_deref(),
694            Some("test-key")
695        );
696    }
697
698    // ── skip_serializing_if tests ─────────────────────────────────────
699
700    #[test]
701    fn empty_vecs_omitted_from_json() {
702        let config = AgentConfig::default();
703        let json = serde_json::to_string(&config).unwrap();
704        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
705        // These should all be absent when empty.
706        for key in &[
707            "workspaces",
708            "tools",
709            "triggers",
710            "hooks",
711            "skills_paths",
712            "mcp_servers",
713        ] {
714            assert!(
715                v.get(key).is_none(),
716                "Empty vec field '{key}' should be omitted from JSON, got: {json}"
717            );
718        }
719        // policies should always be present (non-empty default)
720        assert!(
721            v.get("policies").is_some(),
722            "policies should always be serialized"
723        );
724    }
725
726    #[test]
727    fn populated_vecs_included_in_json() {
728        let config = AgentConfig::builder()
729            .skills(vec![PathBuf::from("/skill.md")])
730            .workspaces(vec![PathBuf::from("/ws")])
731            .build();
732        let json = serde_json::to_string(&config).unwrap();
733        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
734        assert!(
735            v.get("skills_paths").is_some(),
736            "Non-empty skills should be present"
737        );
738        assert!(
739            v.get("workspaces").is_some(),
740            "Non-empty workspaces should be present"
741        );
742    }
743
744    // ── Default policy tests ──────────────────────────────────────────
745
746    #[test]
747    fn default_policies_deny_run_command_allow_rest() {
748        let config = AgentConfig::default();
749        assert_eq!(config.policies.len(), 2);
750        assert_eq!(
751            config.policies[0],
752            PolicyRule::Deny("run_command".to_string())
753        );
754        assert_eq!(config.policies[1], PolicyRule::AllowAll);
755    }
756
757    // ── Python SDK mirror tests ────────────────────────────────────────
758    //
759    // These tests import the live Python SDK and verify that our Rust
760    // constants haven't drifted from the canonical Python values.  They
761    // require `pyo3::Python::initialize()` and a venv with the
762    // SDK installed.
763
764    /// Helper: extract a Python module-level attribute as a `String`.
765    fn py_str_attr(module: &str, attr: &str) -> String {
766        pyo3::Python::initialize();
767        pyo3::Python::attach(|py| {
768            crate::runtime::venv::configure_python_sys_path(py)
769                .unwrap_or_else(|e| panic!("Failed to configure python sys.path: {e}"));
770            let m = py
771                .import(module)
772                .unwrap_or_else(|e| panic!("Failed to import {module}: {e}"));
773            m.getattr(attr)
774                .unwrap_or_else(|e| panic!("Failed to get {module}.{attr}: {e}"))
775                .extract::<String>()
776                .unwrap_or_else(|e| panic!("Failed to extract {module}.{attr} as String: {e}"))
777        })
778    }
779
780    #[test]
781    fn default_model_matches_python_sdk() {
782        let py_val = py_str_attr("google.antigravity.types", "DEFAULT_MODEL");
783        assert_eq!(
784            DEFAULT_MODEL, py_val,
785            "Rust DEFAULT_MODEL ({DEFAULT_MODEL}) != Python SDK ({py_val})"
786        );
787    }
788
789    #[test]
790    fn default_image_model_matches_python_sdk() {
791        let py_val = py_str_attr("google.antigravity.types", "DEFAULT_IMAGE_GENERATION_MODEL");
792        assert_eq!(
793            DEFAULT_IMAGE_GENERATION_MODEL, py_val,
794            "Rust DEFAULT_IMAGE_GENERATION_MODEL ({DEFAULT_IMAGE_GENERATION_MODEL}) != Python SDK ({py_val})"
795        );
796    }
797
798    // ── effective_api_key tests ──────────────────────────────────────
799
800    #[test]
801    fn effective_api_key_prefers_per_model_key() {
802        let config = AgentConfig::builder()
803            .api_key("top-level-key")
804            .gemini(super::super::GeminiConfig {
805                api_key: Some("shared-key".into()),
806                base_url: None,
807                models: super::super::ModelConfig {
808                    default: super::super::ModelEntry {
809                        name: "gemini-3.5-flash".into(),
810                        api_key: Some("per-model-key".into()),
811                        generation: super::super::GenerationConfig::default(),
812                    },
813                    image_generation: super::super::ModelEntry {
814                        name: "imagen-4.0-generate-preview-06-03".into(),
815                        api_key: None,
816                        generation: super::super::GenerationConfig::default(),
817                    },
818                },
819            })
820            .build();
821        assert_eq!(config.effective_api_key().as_deref(), Some("per-model-key"));
822    }
823
824    #[test]
825    fn effective_api_key_falls_back_to_gemini_shared_key() {
826        let config = AgentConfig::builder()
827            .gemini(super::super::GeminiConfig {
828                api_key: Some("shared-key".into()),
829                ..Default::default()
830            })
831            .build();
832        assert_eq!(config.effective_api_key().as_deref(), Some("shared-key"));
833    }
834
835    #[test]
836    fn effective_api_key_falls_back_to_top_level() {
837        let config = AgentConfig::builder().api_key("top-level-key").build();
838        assert_eq!(config.effective_api_key().as_deref(), Some("top-level-key"));
839    }
840
841    #[test]
842    fn effective_api_key_none_without_any_key() {
843        // Build a config with no API key set at any level.
844        // We can't safely manipulate env vars in multi-threaded tests,
845        // so we test the chain up to the env-var fallback: if all config
846        // keys are None and the env var isn't set, the result is None.
847        // If GEMINI_API_KEY happens to be set, we verify it's returned.
848        let config = AgentConfig::builder().build();
849        let result = config.effective_api_key();
850        // NOLINT: .ok() is intentional — env var not set returns None, which is the expected fallback
851        match std::env::var("GEMINI_API_KEY").ok() {
852            Some(env_key) => assert_eq!(result.as_deref(), Some(env_key.as_str())),
853            None => assert!(result.is_none()),
854        }
855    }
856
857    #[test]
858    fn initial_history_empty_by_default() {
859        let config = AgentConfig::default();
860        assert!(config.initial_history.is_empty());
861
862        // Empty initial_history should be skipped in serialization.
863        let json = serde_json::to_string(&config).unwrap();
864        assert!(
865            !json.contains("initial_history"),
866            "empty initial_history should be skipped in JSON"
867        );
868    }
869
870    #[test]
871    fn initial_history_roundtrip() {
872        use crate::types::{ConversationMessage, MessageRole};
873
874        let config = AgentConfig::builder()
875            .initial_history(vec![
876                ConversationMessage {
877                    role: MessageRole::User,
878                    content: "Hello".to_string(),
879                },
880                ConversationMessage {
881                    role: MessageRole::Model,
882                    content: "Hi there!".to_string(),
883                },
884            ])
885            .build();
886
887        assert_eq!(config.initial_history.len(), 2);
888
889        let json = serde_json::to_string(&config).unwrap();
890        assert!(json.contains("initial_history"));
891
892        let parsed: AgentConfig = serde_json::from_str(&json).unwrap();
893        assert_eq!(parsed.initial_history.len(), 2);
894        assert_eq!(parsed.initial_history[0].role, MessageRole::User);
895        assert_eq!(parsed.initial_history[0].content, "Hello");
896        assert_eq!(parsed.initial_history[1].role, MessageRole::Model);
897        assert_eq!(parsed.initial_history[1].content, "Hi there!");
898    }
899}