Skip to main content

agy_bridge/
lib.rs

1#![doc = include_str!("../README.md")]
2//! agy-bridge: Standalone reusable `PyO3` bridge for the Google Antigravity SDK.
3
4// Allow `::agy_bridge::` paths (generated by the `#[llm_tool]` proc macro) to
5// resolve when compiling tests within this crate.
6extern crate self as agy_bridge;
7
8/// Agent lifecycle management: creation, chat, shutdown.
9pub mod agent;
10/// Configuration types for agents, models, capabilities, and MCP servers.
11pub mod config;
12
13/// Multimodal content types for chat input (text, image, document, audio, video).
14pub mod content;
15/// Error types for the bridge.
16pub mod error;
17/// Pre/post-turn and tool-call lifecycle hooks.
18pub mod hooks;
19/// Policy rules for tool-call filtering and workspace scoping.
20pub mod policies;
21/// Python runtime bridge: command dispatch over a dedicated thread.
22pub mod runtime;
23
24/// Streaming response channels for text, thought, and tool-call events.
25pub mod streaming;
26/// Custom Rust tool dispatch and definition types.
27pub mod tools;
28/// Event-driven trigger definitions.
29pub mod triggers;
30/// Shared domain types (messages, steps, usage metadata).
31pub mod types;
32
33// ── Re-exports ──────────────────────────────────────────────────────────────
34// Flat re-exports of the most commonly used types so callers can write
35// `use agy_bridge::{AgentConfig, Error, ToolRegistry, Content};`
36// without diving into sub-modules.
37
38pub use config::{
39    AgentConfig, BuiltinTools, CapabilitiesConfig, GeminiConfig, LocalAgentConfig, McpConfigError,
40    McpConfigFile, McpServer, McpServerSpec, McpSseServer, McpStdioServer, McpStreamableHttpServer,
41    SystemInstructions,
42};
43pub use content::{Audio, Content, ContentPrimitive, Document, Image, Video};
44pub use error::Error;
45pub use hooks::{HookCallback, HookEntry, HookPoint, HookResult, HookSet, Hooks};
46/// Re-export the `#[llm_tool]` proc-macro so users only need `agy_bridge` in
47/// their dependency list.
48pub use llm_tool_macros::llm_tool;
49pub use policies::{AskUserHandler, PolicyDecision, PolicyRule, PolicySet};
50pub use runtime::{BackendLogLevel, RuntimeConfig};
51pub use streaming::{ChatResponseHandle, ChatResult, ResponseEvent, StreamChunk};
52pub use tools::{
53    AvailableTool, RustTool, ToolContext, ToolDefinition, ToolError, ToolOutput, ToolRegistry,
54    ToolSource,
55};
56pub use triggers::{TriggerConfig, TriggerEntry};
57pub use types::{ConversationMessage, MessageRole, Step, UsageMetadata};
58
59/// Convenience prelude — pull in everything you need with a single glob import.
60///
61/// ```
62/// use agy_bridge::prelude::*;
63/// ```
64///
65/// This re-exports the most commonly used types, traits, and macros from the
66/// crate so you can get started quickly without hunting for individual paths.
67pub mod prelude {
68    pub use llm_tool_macros::llm_tool;
69
70    pub use crate::{
71        Agent, AgyBridge,
72        config::{
73            AgentConfig, BuiltinTools, CapabilitiesConfig, GeminiConfig, LocalAgentConfig,
74            McpConfigError, McpConfigFile, McpServer, McpServerSpec, McpSseServer, McpStdioServer,
75            McpStreamableHttpServer, SystemInstructions,
76        },
77        content::{Audio, Content, ContentPrimitive, Document, Image, Video},
78        error::Error,
79        hooks::{HookPoint, HookResult, Hooks},
80        policies::{AskUserHandler, PolicyDecision, PolicyRule, PolicySet},
81        runtime::BackendLogLevel,
82        streaming::{ChatResponseHandle, ChatResult, ResponseEvent, StreamChunk},
83        tools::{
84            AvailableTool, RustTool, ToolContext, ToolDefinition, ToolError, ToolOutput,
85            ToolRegistry, ToolSource,
86        },
87        triggers::{TriggerConfig, TriggerEntry},
88        types::{ConversationMessage, MessageRole, Step, UsageMetadata},
89    };
90}
91
92use std::sync::Arc;
93
94/// Load environment variables from a `.env` file into the process environment.
95///
96/// 1. Walks upward from `CARGO_MANIFEST_DIR` (if set) or the current working
97///    directory to find the nearest `.env` file.
98/// 2. Parses each `KEY=VALUE` line (skipping blanks and `#`-comments).
99/// 3. For every key that is **not** already present in the process
100///    environment, calls [`std::env::set_var`] to inject it.
101/// 4. Returns a [`HashMap`](std::collections::HashMap) of the newly-set
102///    key/value pairs (keys that were already set are omitted).
103///
104/// Results are cached via [`OnceLock`](std::sync::OnceLock) — the file is
105/// read and environment variables are set at most once. Subsequent calls
106/// return a clone of the cached map without re-reading the file or
107/// modifying the environment.
108///
109/// # Safety
110///
111/// This function calls [`std::env::set_var`], which is **not** thread-safe.
112/// It **must** be called during single-threaded startup, before any
113/// additional threads are spawned (including the Tokio runtime). Calling it
114/// after threads exist is undefined behaviour.
115///
116/// # Example
117///
118/// ```
119/// let new_vars = agy_bridge::load_dotenv();
120/// // OnceLock-cached: safe to call multiple times, only loads .env once.
121/// // NOLINT: example code in documentation — `let _ =` demonstrates the return value exists
122/// let _ = new_vars.len();
123/// ```
124pub fn load_dotenv() -> &'static std::collections::HashMap<String, String> {
125    use std::sync::OnceLock;
126
127    static CACHED: OnceLock<std::collections::HashMap<String, String>> = OnceLock::new();
128
129    CACHED.get_or_init(|| {
130        let start = std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(
131            || {
132                std::env::current_dir().unwrap_or_else(|e| {
133                    tracing::debug!("load_dotenv: current_dir() failed: {e}, using fallback \".\"");
134                    std::path::PathBuf::from(".")
135                })
136            },
137            std::path::PathBuf::from,
138        );
139
140        let mut dir = start.as_path();
141        loop {
142            let candidate = dir.join(".env");
143            if candidate.is_file() {
144                let mut env_map = std::collections::HashMap::new();
145                match std::fs::read_to_string(&candidate) {
146                    Ok(contents) => {
147                        for line in contents.lines() {
148                            if let Some((k, v)) = parse_dotenv_line(line)
149                                && std::env::var_os(k).is_none()
150                            {
151                                // SAFETY: Called inside the OnceLock closure during
152                                // single-threaded initialization, before any threads
153                                // are spawned. set_var is not thread-safe, but here
154                                // we are the only thread.
155                                unsafe {
156                                    std::env::set_var(k, v);
157                                }
158                                env_map.insert(k.to_owned(), v.to_owned());
159                            }
160                        }
161                    }
162                    Err(e) => {
163                        tracing::warn!(error = %e, "Failed to read .env file at {}", candidate.display());
164                    }
165                }
166                return env_map;
167            }
168            match dir.parent() {
169                Some(parent) => dir = parent,
170                None => return std::collections::HashMap::new(),
171            }
172        }
173    })
174}
175
176/// Parse a single line from a `.env` file.
177///
178/// Returns `Some((key, value))` for valid `KEY=VALUE` lines, stripping
179/// surrounding whitespace and quotes (single or double) from the value.
180/// Returns `None` for blank lines, comments, or lines without `=`.
181///
182/// This is factored out of [`load_dotenv`] for testability.
183pub(crate) fn parse_dotenv_line(line: &str) -> Option<(&str, &str)> {
184    let line = line.trim();
185    if line.is_empty() || line.starts_with('#') {
186        return None;
187    }
188    let (k, v) = line.split_once('=')?;
189    let k = k.trim();
190    if k.is_empty() {
191        return None;
192    }
193    let v = v.trim();
194    // Strip surrounding quotes (single or double)
195    let v = v
196        .strip_prefix('"')
197        .and_then(|s| s.strip_suffix('"'))
198        .or_else(|| v.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
199        .unwrap_or(v);
200    Some((k, v))
201}
202
203/// Convenience alias for an agent backed by the bridge's runtime.
204///
205/// This hides the generic `Runtime` parameter so consumers never see the
206/// underlying Python bridge type.
207pub type Agent = agent::AgentHandle<runtime::PythonRuntime>;
208
209/// Primary entry point for the Antigravity bridge.
210///
211/// Wraps the runtime and provides a clean Rust API for creating agents.
212///
213/// # Example
214///
215/// ```rust
216/// # use agy_bridge::AgyBridge;
217/// # use agy_bridge::config::AgentConfig;
218/// # #[tokio::main]
219/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
220/// # agy_bridge::load_dotenv();
221/// // Zero-config:
222/// // let bridge = AgyBridge::builder().build()?;
223///
224/// // With custom settings:
225/// let bridge = AgyBridge::builder().channel_capacity(128).build()?;
226///
227/// // Create an agent (simple):
228/// // let agent = bridge.agent(AgentConfig::default()).await?;
229/// # let manifest_dir = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
230/// # let project_root = manifest_dir.parent().unwrap().parent().unwrap();
231/// # let agent = bridge.agent(
232/// #     AgentConfig::builder()
233/// #         .system_instructions("Reply with 'Hello!' and nothing else. Never use tools.")
234/// #         .capabilities(agy_bridge::config::CapabilitiesConfig::custom_tools_only())
235/// #         .workspaces(vec![project_root])
236/// #         .build()
237/// # ).await?;
238///
239/// // Create an agent with tools and hooks:
240/// // let agent = bridge.agent(config)
241/// //     .tools(registry)
242/// //     .hooks(hooks)
243/// //     .await?;
244///
245/// let answer = agent.chat("Hello!").await?.text().await?;
246/// # Ok(())
247/// # }
248/// ```
249pub struct AgyBridge {
250    runtime: Arc<runtime::PythonRuntime>,
251}
252
253/// Builder for constructing an [`AgyBridge`] instance.
254///
255/// Created via [`AgyBridge::builder()`]. All settings have sensible defaults;
256/// call [`.build()`](Self::build) to finalise.
257///
258/// # Example
259///
260/// ```
261/// # use agy_bridge::AgyBridge;
262/// let bridge = AgyBridge::builder().channel_capacity(128).build()?;
263/// # Ok::<(), agy_bridge::error::Error>(())
264/// ```
265pub struct AgyBridgeBuilder {
266    config: runtime::RuntimeConfig,
267}
268
269impl AgyBridgeBuilder {
270    /// Set the mpsc channel buffer size for the command channel.
271    #[must_use]
272    pub fn channel_capacity(mut self, capacity: usize) -> Self {
273        self.config.channel_capacity = capacity;
274        self
275    }
276
277    /// Set the timeout for joining the Python thread on shutdown.
278    #[must_use]
279    pub fn shutdown_timeout(mut self, timeout: std::time::Duration) -> Self {
280        self.config.shutdown_timeout = timeout;
281        self
282    }
283
284    /// Set the delay between successive chat commands to prevent burst requests.
285    #[must_use]
286    pub fn inter_agent_delay(mut self, delay: std::time::Duration) -> Self {
287        self.config.inter_agent_delay = delay;
288        self
289    }
290
291    /// Set the backend runtime log verbosity.
292    ///
293    /// Defaults to [`BackendLogLevel::Warn`]. Set to [`BackendLogLevel::Info`]
294    /// or [`BackendLogLevel::Debug`] for verbose protocol-level diagnostics.
295    #[must_use]
296    pub fn backend_log_level(mut self, level: runtime::BackendLogLevel) -> Self {
297        self.config.backend_log_level = level;
298        self
299    }
300
301    /// Replace the entire runtime configuration at once.
302    ///
303    /// Useful when you already have a [`RuntimeConfig`] struct. Individual
304    /// setters called *after* this will override the corresponding fields.
305    #[must_use]
306    pub fn runtime_config(mut self, config: runtime::RuntimeConfig) -> Self {
307        self.config = config;
308        self
309    }
310
311    /// Set the maximum number of consecutive model-quality errors before
312    /// aborting a stream. Set to `0` to disable entirely (pure SDK pass-through).
313    ///
314    /// Defaults to `3` — enough to catch deterministically-bad model output
315    /// without cutting off transient hiccups.
316    #[must_use]
317    pub fn max_consecutive_model_errors(mut self, limit: u32) -> Self {
318        self.config.max_consecutive_model_errors = Some(limit);
319        self
320    }
321
322    /// Set the maximum number of consecutive thinking-only/empty steps before
323    /// aborting a stream. Set to `0` to disable entirely (pure SDK pass-through).
324    ///
325    /// Defaults to `500` — a generous ceiling to avoid false positives on
326    /// legitimate long chains of thought.
327    #[must_use]
328    pub fn max_consecutive_empty_steps(mut self, limit: u32) -> Self {
329        self.config.max_consecutive_empty_steps = Some(limit);
330        self
331    }
332
333    /// Set the per-channel buffer size for streaming response channels.
334    ///
335    /// Each chat call creates ~7 channels of this size. Defaults to `256` —
336    /// large enough to avoid backpressure under normal workloads.
337    #[must_use]
338    pub fn streaming_channel_buffer(mut self, size: usize) -> Self {
339        self.config.streaming_channel_buffer = Some(size);
340        self
341    }
342
343    /// Build the [`AgyBridge`], starting the Python runtime.
344    ///
345    /// # Errors
346    ///
347    /// Returns [`error::Error`] if the Python runtime cannot be started
348    /// (e.g. missing Antigravity SDK installation).
349    pub fn build(self) -> Result<AgyBridge, error::Error> {
350        Ok(AgyBridge {
351            runtime: Arc::new(runtime::PythonRuntime::new(self.config)?),
352        })
353    }
354}
355
356impl AgyBridge {
357    /// Create a new builder for configuring and constructing an [`AgyBridge`].
358    ///
359    /// # Example
360    ///
361    /// ```
362    /// # use agy_bridge::AgyBridge;
363    /// let bridge = AgyBridge::builder().build()?;
364    /// # Ok::<(), agy_bridge::error::Error>(())
365    /// ```
366    #[must_use]
367    pub fn builder() -> AgyBridgeBuilder {
368        AgyBridgeBuilder {
369            config: runtime::RuntimeConfig::default(),
370        }
371    }
372
373    /// Begin building a new agent on this bridge.
374    ///
375    /// Returns an [`AgentBuilder`] that can be directly `.await`ed for the
376    /// simple case, or chained with [`.tools()`](AgentBuilder::tools) and
377    /// [`.hooks()`](AgentBuilder::hooks) before awaiting.
378    ///
379    /// # Examples
380    ///
381    /// ```rust
382    /// # use agy_bridge::{AgyBridge, config::AgentConfig};
383    /// # #[tokio::main]
384    /// # async fn main() -> Result<(), agy_bridge::error::Error> {
385    /// # agy_bridge::load_dotenv();
386    /// # let bridge = AgyBridge::builder().build()?;
387    /// // Simple — no tools or hooks:
388    /// let agent = bridge.agent(AgentConfig::default()).await?;
389    ///
390    /// // With tools:
391    /// // let agent = bridge.agent(config).tools(registry).await?;
392    ///
393    /// // With tools and hooks:
394    /// // let agent = bridge.agent(config).tools(registry).hooks(hooks).await?;
395    /// # Ok(())
396    /// # }
397    /// ```
398    #[must_use]
399    pub fn agent(&self, config: config::AgentConfig) -> AgentBuilder<'_> {
400        AgentBuilder {
401            bridge: self,
402            config,
403            registry: None,
404            hooks: None,
405            policy_handler: None,
406        }
407    }
408
409    /// Convenience shorthand for `self.agent(AgentConfig::default())`.
410    ///
411    /// Creates an agent builder with default configuration. Chain
412    /// [`.tools()`](AgentBuilder::tools) or [`.hooks()`](AgentBuilder::hooks)
413    /// before awaiting, or `.await` directly for a bare agent.
414    ///
415    /// # Examples
416    ///
417    /// ```rust
418    /// # use agy_bridge::AgyBridge;
419    /// # #[tokio::main]
420    /// # async fn main() -> Result<(), agy_bridge::error::Error> {
421    /// # agy_bridge::load_dotenv();
422    /// # let bridge = AgyBridge::builder().build()?;
423    /// let agent = bridge.default_agent().await?;
424    /// # Ok(())
425    /// # }
426    /// ```
427    #[must_use]
428    pub fn default_agent(&self) -> AgentBuilder<'_> {
429        self.agent(config::AgentConfig::default())
430    }
431
432    /// Return the number of agents currently live on this bridge.
433    ///
434    /// Counts agents that have been created but not yet shut down or dropped.
435    /// Because a bridge owns a single runtime with a single agent registry,
436    /// this reflects exactly the agents belonging to *this* bridge — it is
437    /// unaffected by agents on other [`AgyBridge`] instances.
438    ///
439    /// Useful for observability and for asserting clean teardown: once every
440    /// agent has been shut down or dropped, the count returns to zero.
441    ///
442    /// # Errors
443    ///
444    /// Returns [`error::Error`] if the runtime thread has exited.
445    pub async fn active_agent_count(&self) -> Result<usize, error::Error> {
446        self.runtime.active_agent_count().await
447    }
448}
449
450/// Builder for creating an [`Agent`] on an [`AgyBridge`].
451///
452/// Obtained from [`AgyBridge::agent()`]. Implements [`IntoFuture`] so you can
453/// `.await` it directly, or chain optional [`.tools()`](Self::tools) /
454/// [`.hooks()`](Self::hooks) calls before awaiting.
455pub struct AgentBuilder<'a> {
456    bridge: &'a AgyBridge,
457    config: config::AgentConfig,
458    registry: Option<tools::ToolRegistry>,
459    hooks: Option<hooks::Hooks>,
460    policy_handler: Option<Arc<dyn policies::AskUserHandler>>,
461}
462
463impl AgentBuilder<'_> {
464    /// Attach a [`ToolRegistry`] containing custom
465    /// Rust tools for the agent.
466    ///
467    /// The registry's tool definitions are automatically merged into the
468    /// agent configuration.
469    ///
470    /// # Errors (at build time)
471    ///
472    /// Returns [`error::Error::InvalidConfig`] if `config.tools` is
473    /// already non-empty — pass tools via the registry **or** via
474    /// `config.tools`, not both.
475    #[must_use]
476    pub fn tools(mut self, registry: tools::ToolRegistry) -> Self {
477        self.registry = Some(registry);
478        self
479    }
480
481    /// Attach [`Hooks`] for lifecycle event
482    /// callbacks (pre/post turn, tool-call gating, etc.).
483    #[must_use]
484    pub fn hooks(mut self, hooks: hooks::Hooks) -> Self {
485        self.hooks = Some(hooks);
486        self
487    }
488
489    /// Attach a custom [`AskUserHandler`] to manage interactive tool-call confirmations.
490    #[must_use]
491    pub fn policy_handler(mut self, handler: impl policies::AskUserHandler + 'static) -> Self {
492        self.policy_handler = Some(Arc::new(handler));
493        self
494    }
495
496    /// Resume an existing conversation by its SDK id.
497    ///
498    /// Set this to an id previously returned by
499    /// [`AgentHandle::conversation_id`](agent::AgentHandle::conversation_id) to
500    /// resume that conversation. The local harness uses it as the trajectory
501    /// `cascade_id` to reload, so it **must** reference a conversation already
502    /// persisted under the agent's `save_dir`; an unknown id fails agent
503    /// creation with "conversation not found".
504    ///
505    /// Leave this unset to start a fresh conversation — the harness assigns a
506    /// new id, observable afterwards via
507    /// [`AgentHandle::conversation_id`](agent::AgentHandle::conversation_id) and
508    /// custom-tool [`ToolContext::conversation_id`](tools::ToolContext). To
509    /// resume later, persist that id together with the same `save_dir`.
510    #[must_use]
511    pub fn conversation_id(mut self, id: impl Into<String>) -> Self {
512        self.config.conversation_id = Some(id.into());
513        self
514    }
515
516    /// Set the model backend (e.g. `"gemini-3.5-flash"`).
517    #[must_use]
518    pub fn model(mut self, model: impl Into<String>) -> Self {
519        self.config.model = model.into();
520        self
521    }
522
523    /// Set system instructions for the agent.
524    #[must_use]
525    pub fn system_instructions(
526        mut self,
527        instructions: impl Into<config::SystemInstructions>,
528    ) -> Self {
529        self.config.system_instructions = Some(instructions.into());
530        self
531    }
532
533    /// Append workspace directories the agent is allowed to access and modify.
534    #[must_use]
535    pub fn workspaces(
536        mut self,
537        workspaces: impl IntoIterator<Item = impl Into<std::path::PathBuf>>,
538    ) -> Self {
539        self.config
540            .workspaces
541            .extend(workspaces.into_iter().map(Into::into));
542        self
543    }
544
545    /// Append policy rules to govern tool execution.
546    #[must_use]
547    pub fn policies(
548        mut self,
549        policies: impl IntoIterator<Item = impl Into<policies::PolicyRule>>,
550    ) -> Self {
551        self.config
552            .policies
553            .extend(policies.into_iter().map(Into::into));
554        self
555    }
556
557    /// Append triggers that autonomously wake the agent.
558    #[must_use]
559    pub fn triggers(
560        mut self,
561        triggers: impl IntoIterator<Item = impl Into<triggers::TriggerEntry>>,
562    ) -> Self {
563        self.config
564            .triggers
565            .extend(triggers.into_iter().map(Into::into));
566        self
567    }
568
569    /// Append MCP servers for the agent.
570    #[must_use]
571    pub fn mcp_servers(
572        mut self,
573        servers: impl IntoIterator<Item = impl Into<config::McpServer>>,
574    ) -> Self {
575        self.config
576            .mcp_servers
577            .extend(servers.into_iter().map(Into::into));
578        self
579    }
580
581    /// Append paths for agent skills.
582    #[must_use]
583    pub fn skills(
584        mut self,
585        skills: impl IntoIterator<Item = impl Into<std::path::PathBuf>>,
586    ) -> Self {
587        self.config
588            .skills
589            .extend(skills.into_iter().map(Into::into));
590        self
591    }
592
593    /// Validate configuration and create the agent.
594    ///
595    /// Prefer using `.await` directly on the builder (via [`IntoFuture`])
596    /// instead of calling this method explicitly.
597    ///
598    /// # Errors
599    ///
600    /// Returns [`error::Error::InvalidConfig`] if:
601    /// - `config.tools` is non-empty **and** a `ToolRegistry` was provided.
602    /// - The capabilities configuration is self-contradictory (e.g. both
603    ///   `enabled_tools` and `disabled_tools` specified).
604    ///
605    /// Returns other [`error::Error`] variants if agent creation fails.
606    pub async fn build(mut self) -> Result<Agent, error::Error> {
607        // Validate capabilities.
608        if let Some(ref caps) = self.config.capabilities {
609            caps.validate().map_err(|msg| error::Error::InvalidConfig {
610                message: msg.to_string(),
611            })?;
612        }
613
614        // Handle tool registry.
615        let arc_registry = if let Some(registry) = self.registry {
616            if !self.config.tools.is_empty() {
617                return Err(error::Error::InvalidConfig {
618                    message: "config.tools is non-empty and a ToolRegistry was also provided; \
619                              pass tools via the registry or via config.tools, not both"
620                        .to_string(),
621                });
622            }
623            self.config.tools = registry.definitions();
624            Some(Arc::new(registry))
625        } else {
626            None
627        };
628
629        // Handle hooks.
630        let arc_hooks = if let Some(hooks) = self.hooks {
631            if !self.config.hooks.is_empty() {
632                return Err(error::Error::InvalidConfig {
633                    message: "config.hooks is non-empty and a Hooks instance was also provided; \
634                              configure hooks via Hooks or config.hooks, not both"
635                        .to_string(),
636                });
637            }
638            self.config.hooks = hooks.entries();
639            Some(Arc::new(hooks))
640        } else {
641            None
642        };
643
644        // Handle policy handler.
645        let arc_policy = self.policy_handler;
646
647        agent::AgentHandle::new(
648            Arc::clone(&self.bridge.runtime),
649            self.config,
650            arc_registry,
651            arc_hooks,
652            arc_policy,
653        )
654        .await
655    }
656}
657
658impl<'a> std::future::IntoFuture for AgentBuilder<'a> {
659    type Output = Result<Agent, error::Error>;
660    type IntoFuture =
661        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;
662
663    fn into_future(self) -> Self::IntoFuture {
664        Box::pin(self.build())
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671
672    // ── parse_dotenv_line regression tests ────────────────────────────
673
674    #[test]
675    fn dotenv_strips_double_quotes() {
676        let (k, v) = parse_dotenv_line(r#"API_KEY="my-secret""#).unwrap();
677        assert_eq!(k, "API_KEY");
678        assert_eq!(v, "my-secret");
679    }
680
681    #[test]
682    fn dotenv_strips_single_quotes() {
683        let (k, v) = parse_dotenv_line("TOKEN='abc123'").unwrap();
684        assert_eq!(k, "TOKEN");
685        assert_eq!(v, "abc123");
686    }
687
688    #[test]
689    fn dotenv_unquoted_value_unchanged() {
690        let (k, v) = parse_dotenv_line("FOO=bar").unwrap();
691        assert_eq!(k, "FOO");
692        assert_eq!(v, "bar");
693    }
694
695    #[test]
696    fn dotenv_mismatched_quotes_preserved() {
697        // Opening double quote but closing single quote → not stripped.
698        let (k, v) = parse_dotenv_line(r#"KEY="value'"#).unwrap();
699        assert_eq!(k, "KEY");
700        assert_eq!(v, r#""value'"#);
701    }
702
703    #[test]
704    fn dotenv_empty_quoted_value() {
705        let (k, v) = parse_dotenv_line(r#"EMPTY="""#).unwrap();
706        assert_eq!(k, "EMPTY");
707        assert_eq!(v, "");
708    }
709
710    #[test]
711    fn dotenv_whitespace_around_key_value() {
712        let (k, v) = parse_dotenv_line("  MY_VAR  =  \"hello world\"  ").unwrap();
713        assert_eq!(k, "MY_VAR");
714        assert_eq!(v, "hello world");
715    }
716
717    #[test]
718    fn dotenv_comment_line_is_none() {
719        assert!(parse_dotenv_line("# this is a comment").is_none());
720    }
721
722    #[test]
723    fn dotenv_blank_line_is_none() {
724        assert!(parse_dotenv_line("   ").is_none());
725    }
726
727    #[test]
728    fn dotenv_empty_key_is_none() {
729        assert!(parse_dotenv_line("=value").is_none());
730    }
731
732    #[test]
733    fn dotenv_no_equals_is_none() {
734        assert!(parse_dotenv_line("JUSTKEY").is_none());
735    }
736
737    #[test]
738    fn dotenv_value_with_internal_equals() {
739        let (k, v) = parse_dotenv_line("DSN=postgres://host:5432/db?opt=1").unwrap();
740        assert_eq!(k, "DSN");
741        assert_eq!(v, "postgres://host:5432/db?opt=1");
742    }
743
744    #[test]
745    fn dotenv_value_with_embedded_quotes_not_stripped() {
746        // Quotes in the middle are not stripped — only surrounding ones.
747        let (k, v) = parse_dotenv_line(r#"MSG=say "hello""#).unwrap();
748        assert_eq!(k, "MSG");
749        assert_eq!(v, r#"say "hello""#);
750    }
751
752    #[test]
753    fn test_load_dotenv_returns_static_reference_identity() {
754        let map1 = load_dotenv();
755        let map2 = load_dotenv();
756        assert!(std::ptr::eq(map1, map2));
757    }
758}