Skip to main content

ai_agents/
lib.rs

1//! # AI Agents Framework
2//!
3//! **One YAML = Any Agent.** A Rust framework for building AI agents from a single YAML
4//! specification. No code required for common use cases.
5//!
6//! # Quick Start
7//!
8//! ### From YAML
9//!
10//! ```rust,ignore
11//! use ai_agents::{Agent, AgentBuilder};
12//!
13//! #[tokio::main]
14//! async fn main() -> ai_agents::Result<()> {
15//!     let agent = AgentBuilder::from_yaml_file("agent.yaml")?
16//!         .auto_configure_llms()?
17//!         .auto_configure_features()?
18//!         .auto_configure_mcp().await?
19//!         .auto_configure_spawner().await?
20//!         .build()?;
21//!
22//!     let response = agent.chat("Hello!").await?;
23//!     println!("{}", response.content);
24//!     Ok(())
25//! }
26//! ```
27//!
28//! ### From Rust API
29//!
30//! ```rust,ignore
31//! use ai_agents::{Agent, AgentBuilder, UnifiedLLMProvider, ProviderType};
32//! use std::sync::Arc;
33//!
34//! #[tokio::main]
35//! async fn main() -> ai_agents::Result<()> {
36//!     let llm = UnifiedLLMProvider::from_env(ProviderType::OpenAI, "gpt-5.4-nano")?;
37//!
38//!     let agent = AgentBuilder::new()
39//!         .system_prompt("You are a helpful assistant.")
40//!         .llm(Arc::new(llm))
41//!         .build()?;
42//!
43//!     let response = agent.chat("Hello!").await?;
44//!     println!("{}", response.content);
45//!     Ok(())
46//! }
47//! ```
48//!
49//! # Modules
50//!
51//! | Module | Description |
52//! |--------|-------------|
53//! | [`agent`] | Agent builder, runtime, streaming, and response types |
54//! | [`llm`] | LLM providers and registry |
55//! | [`memory`] | Conversation memory with compression and token budgeting |
56//! | [`tools`] | Built-in tools and extensible tool registry |
57//! | [`state`] | Hierarchical state machine with LLM-evaluated transitions |
58//! | [`context`] | Dynamic context injection from multiple sources |
59//! | [`skill`] | Reusable workflows with LLM-based intent routing |
60//! | [`hitl`] | Human-in-the-loop approval system |
61//! | [`reasoning`] | Chain-of-thought, ReAct, plan-and-execute modes |
62//! | [`disambiguation`] | Intent ambiguity detection and clarification |
63//! | [`persistence`] | SQLite, Redis, and file storage backends |
64//! | [`process`] | Input/output processing pipeline |
65//! | [`recovery`] | Error recovery with retry and fallback strategies |
66//! | [`hooks`] | Lifecycle event hooks for logging, metrics, monitoring |
67//! | [`spec`] | YAML agent specification types |
68//! | [`template`] | Template loading with Jinja2 rendering and inheritance |
69//! | [`spawner`] | Dynamic agent spawning, registry, and inter-agent messaging |
70//! | [`observability`] | Latency, token, cost, trace, and export metrics |
71//!
72//! # Feature Flags
73//!
74//! | Flag | Description |
75//! |------|-------------|
76//! | `sqlite` | SQLite storage backend |
77//! | `redis-storage` | Redis storage backend |
78//! | `http-context` | HTTP context source for dynamic context injection |
79//! | `full-storage` | All storage backends (`sqlite` + `redis-storage`) |
80//! | `full` | All optional features enabled |
81
82pub mod agent {
83    pub use ai_agents_runtime::{
84        Agent, AgentBuilder, AgentInfo, AgentResponse, AgentStreamEvent, AwaitBeforeNextTurn,
85        BackgroundOverflowPolicy, MainResponseDraft, MaintenanceMode, MaintenanceTaskPolicy,
86        ParallelToolsConfig, PostTurnOptimizationConfig, RuntimeAgent, RuntimeBranch,
87        RuntimeBranchOutcome, RuntimeBranchResult, RuntimeBranchStatus, RuntimeCommitBehavior,
88        RuntimeConfig, RuntimeControlHandle, RuntimeOptimizationConfig, RuntimeOptimizationKind,
89        RuntimeTaskPriority, RuntimeTaskPurpose, ScheduledBranchSet, SkillCandidate,
90        StreamBranchBuffer, StreamChunk, StreamingConfig, StreamingDraftResult,
91        StreamingOptimizationPolicy, ToolCall, TurnActorContext, TurnBranchScheduler,
92        TurnOptimizationContext,
93    };
94}
95
96pub mod context {
97    pub use ai_agents_context::{
98        BuiltinSource, ContextManager, ContextProvider, ContextSource, RefreshPolicy,
99        TemplateRenderer,
100    };
101}
102
103pub mod error {
104    pub use ai_agents_core::{AgentError, Result};
105}
106
107pub mod dot_path {
108    pub use ai_agents_core::{get_dot_path, get_dot_path_from_map, set_dot_path};
109}
110
111pub mod hitl {
112    pub use ai_agents_hitl::{
113        ApprovalCondition, ApprovalHandler, ApprovalMessage, ApprovalRequest,
114        ApprovalResolvedOutcome, ApprovalResult, ApprovalTrigger, AutoApproveHandler,
115        CallbackHandler, HITLCheckResult, HITLConfig, HITLEngine, LlmGenerateConfig,
116        LocalizedHandler, MessageLanguageConfig, MessageLanguageStrategy, MessageResolver,
117        RejectAllHandler, StateApprovalConfig, StateApprovalTrigger, TimeoutAction,
118        ToolApprovalConfig, create_handler, create_localized_handler, resolve_best_language,
119        resolve_tool_message,
120    };
121}
122
123pub mod hooks {
124    pub use ai_agents_hooks::{AgentHooks, CompositeHooks, HookTimer, LoggingHooks, NoopHooks};
125}
126
127pub mod llm {
128    pub use ai_agents_core::{
129        ChatMessage, FinishReason, LLMCapability, LLMChunk, LLMConfig, LLMError, LLMFeature,
130        LLMProvider, LLMResponse, LLMToolDefinition, LLMToolRequest, Role, TaskContext, TokenUsage,
131        ToolChoice, ToolSelection,
132    };
133    pub use ai_agents_llm::LLMRegistry;
134    pub use ai_agents_llm::multi::MultiLLMRouter;
135
136    pub mod providers {
137        pub use ai_agents_llm::providers::{ProviderBuilder, ProviderType, UnifiedLLMProvider};
138    }
139}
140
141pub mod memory {
142    use std::sync::Arc;
143
144    use ai_agents_core::LLMProvider;
145
146    pub use ai_agents_core::MemorySnapshot;
147    pub use ai_agents_memory::{
148        CompactingMemory, CompactingMemoryConfig, CompressResult, CompressionEvent,
149        ConversationContext, EvictionReason, FactExtractedEvent, InMemoryStore, LLMSummarizer,
150        Memory, MemoryBudgetEvent, MemoryBudgetState, MemoryCompressEvent, MemoryEvictEvent,
151        MemoryTokenBudget, NoopSummarizer, OverflowStrategy, Summarizer, TokenAllocation,
152        estimate_message_tokens, estimate_tokens,
153    };
154    pub use ai_agents_runtime::spec::MemoryConfig;
155
156    pub fn create_memory(memory_type: &str, max_messages: usize) -> Arc<dyn Memory> {
157        match memory_type {
158            "in-memory" => Arc::new(InMemoryStore::new(max_messages)),
159            "compacting" => {
160                let summarizer: Arc<dyn Summarizer> = Arc::new(NoopSummarizer);
161                Arc::new(CompactingMemory::with_default_config(summarizer))
162            }
163            _ => Arc::new(InMemoryStore::new(max_messages)),
164        }
165    }
166
167    pub fn create_memory_from_config(config: &MemoryConfig) -> Arc<dyn Memory> {
168        if config.is_compacting() {
169            let summarizer: Arc<dyn Summarizer> = Arc::new(NoopSummarizer);
170            let compacting_config = config.to_compacting_config();
171            Arc::new(CompactingMemory::new(summarizer, compacting_config))
172        } else {
173            Arc::new(InMemoryStore::new(config.max_messages))
174        }
175    }
176
177    pub fn create_memory_from_config_with_llm(
178        config: &MemoryConfig,
179        llm: Option<Arc<dyn LLMProvider>>,
180    ) -> Arc<dyn Memory> {
181        if config.is_compacting() {
182            let summarizer: Arc<dyn Summarizer> = match llm {
183                Some(provider) => Arc::new(LLMSummarizer::new(provider)),
184                None => Arc::new(NoopSummarizer),
185            };
186            let compacting_config = config.to_compacting_config();
187            Arc::new(CompactingMemory::new(summarizer, compacting_config))
188        } else {
189            Arc::new(InMemoryStore::new(config.max_messages))
190        }
191    }
192
193    pub fn create_compacting_memory(
194        summarizer: Arc<dyn Summarizer>,
195        config: CompactingMemoryConfig,
196    ) -> Arc<dyn Memory> {
197        Arc::new(CompactingMemory::new(summarizer, config))
198    }
199
200    pub fn create_compacting_memory_from_config(
201        summarizer: Arc<dyn Summarizer>,
202        config: &MemoryConfig,
203    ) -> Arc<dyn Memory> {
204        let compacting_config = config.to_compacting_config();
205        Arc::new(CompactingMemory::new(summarizer, compacting_config))
206    }
207}
208
209pub mod persistence {
210    use std::sync::Arc;
211
212    pub use ai_agents_core::{
213        AgentSnapshot, AgentStorage, MemorySnapshot, NoopStorage, Result, SpawnedAgentEntry,
214        StorageCapability,
215    };
216    #[cfg(feature = "sqlite")]
217    pub use ai_agents_storage::SqliteStorage;
218    pub use ai_agents_storage::{
219        FileStorage, SessionInfo, SessionMetadata, SessionOrderBy, SessionQuery,
220    };
221    #[cfg(feature = "redis-storage")]
222    pub use ai_agents_storage::{RedisSessionMeta, RedisStorage};
223
224    pub async fn create_storage(
225        config: &crate::spec::StorageConfig,
226    ) -> Result<Option<Arc<dyn AgentStorage>>> {
227        let storage_config = match config {
228            crate::spec::StorageConfig::None => ai_agents_storage::StorageConfig::None,
229            crate::spec::StorageConfig::File(fc) => ai_agents_storage::StorageConfig::File {
230                path: fc.path.clone(),
231            },
232            crate::spec::StorageConfig::Sqlite(sc) => ai_agents_storage::StorageConfig::Sqlite {
233                path: sc.path.clone(),
234            },
235            crate::spec::StorageConfig::Redis(rc) => ai_agents_storage::StorageConfig::Redis {
236                url: rc.url.clone(),
237                prefix: rc.prefix.clone(),
238                ttl_seconds: rc.ttl_seconds,
239            },
240        };
241
242        ai_agents_storage::create_storage(&storage_config).await
243    }
244}
245
246pub mod process {
247    pub use ai_agents_process::{ProcessConfig, ProcessData, ProcessProcessor};
248}
249
250pub mod recovery {
251    pub use ai_agents_recovery::{
252        ByRoleFilter, ErrorRecoveryConfig, FilterConfig, KeepRecentFilter, MessageFilter,
253        RecoveryManager, SkipPatternFilter,
254    };
255}
256
257pub mod skill {
258    pub use ai_agents_skills::{
259        SkillContext, SkillDefinition, SkillExecutor, SkillLoader, SkillRef, SkillRouter,
260        SkillStep, StepResult,
261    };
262}
263
264pub mod spec {
265    pub use ai_agents_observability::ObservabilityConfig;
266    pub use ai_agents_runtime::spec::{
267        AgentSpec, AutoSpawnEntry, CliHitlMetadata, CliHitlStyle, CliMetadata, CliPromptStyle,
268        FileStorageConfig, LLMConfig, LLMConfigOrSelector, LLMSelector, ManagementToolsConfig,
269        MemoryConfig, OrchestrationToolsConfig, RedisStorageConfig, RuntimeConfig, SpawnerConfig,
270        SpawnerToolGrantConfig, SqliteStorageConfig, StorageConfig, StructuredToolEntry,
271        TemplateSource, ToolAliasesConfig, ToolConfig, ToolEntry,
272    };
273}
274
275pub mod state {
276    pub use ai_agents_state::{
277        CompareOp, ContextExtractor, ContextMatcher, DelegateContextMode, GuardConditions,
278        GuardOnlyEvaluator, HandoffStateConfig, LLMTransitionEvaluator, PipelineStageEntry,
279        PipelineStateConfig, PromptMode, StateAction, StateConfig, StateDefinition, StateMachine,
280        StateMachineSnapshot, StateMatcher, StateTransitionEvent, TimeMatcher, ToolCondition,
281        ToolRef, Transition, TransitionContext, TransitionEvaluator, TransitionGuard,
282        TransitionTiming,
283    };
284}
285
286pub mod template {
287    use std::collections::HashMap;
288    use std::path::PathBuf;
289
290    use ai_agents_template::TemplateLoader as InnerTemplateLoader;
291    pub use ai_agents_template::{TemplateInheritance, TemplateRenderer};
292
293    use crate::error::Result;
294    use crate::spec::AgentSpec;
295
296    pub struct TemplateLoader {
297        inner: InnerTemplateLoader,
298    }
299
300    impl TemplateLoader {
301        pub fn new() -> Self {
302            Self {
303                inner: InnerTemplateLoader::new(),
304            }
305        }
306
307        pub fn add_search_path(&mut self, path: impl Into<PathBuf>) -> &mut Self {
308            self.inner.add_search_path(path);
309            self
310        }
311
312        pub fn set_variable(
313            &mut self,
314            key: impl Into<String>,
315            value: impl Into<String>,
316        ) -> &mut Self {
317            self.inner.set_variable(key, value);
318            self
319        }
320
321        pub fn set_variables(&mut self, vars: HashMap<String, String>) -> &mut Self {
322            self.inner.set_variables(vars);
323            self
324        }
325
326        pub fn get_variable(&self, key: &str) -> Option<&str> {
327            self.inner.get_variable(key)
328        }
329
330        pub fn load_template(&self, name: &str) -> Result<String> {
331            self.inner.load_template(name)
332        }
333
334        pub fn template_exists(&self, name: &str) -> bool {
335            self.inner.template_exists(name)
336        }
337
338        pub fn search_paths(&self) -> &[PathBuf] {
339            self.inner.search_paths()
340        }
341
342        pub fn variables(&self) -> &HashMap<String, String> {
343            self.inner.variables()
344        }
345
346        pub fn load_and_parse(&self, template_name: &str) -> Result<AgentSpec> {
347            let renderer = TemplateRenderer::new();
348            let variables = self.variables();
349
350            let load_and_render = |name: &str| -> Result<String> {
351                let content = self.load_template(name)?;
352                renderer.render(&content, variables)
353            };
354
355            let rendered_root = load_and_render(template_name)?;
356            let processed = TemplateInheritance::process(&rendered_root, load_and_render)?;
357            let spec = AgentSpec::from_yaml_strict(&processed)?;
358            spec.validate()?;
359
360            Ok(spec)
361        }
362    }
363
364    impl Default for TemplateLoader {
365        fn default() -> Self {
366            Self::new()
367        }
368    }
369
370    impl AsRef<InnerTemplateLoader> for TemplateLoader {
371        fn as_ref(&self) -> &InnerTemplateLoader {
372            &self.inner
373        }
374    }
375
376    impl From<InnerTemplateLoader> for TemplateLoader {
377        fn from(inner: InnerTemplateLoader) -> Self {
378            Self { inner }
379        }
380    }
381}
382
383pub mod persona {
384    pub use ai_agents_persona::{
385        EvolutionConfig, PERSONA_CHANGE_METADATA_KEY, PersonaChange, PersonaConfig,
386        PersonaEvolveTool, PersonaGoals, PersonaIdentity, PersonaManager, PersonaRenderResult,
387        PersonaSecret, PersonaSnapshot, PersonaTemplateRef, PersonaTemplateRegistry, PersonaTraits,
388        SecretRevealCondition, VALID_EVOLVE_PATHS,
389    };
390}
391
392pub mod relationships {
393    pub use ai_agents_relationships::{
394        AutoUpdateConfig, DimensionChange, EventEvictionStrategy, InjectionConfig, InjectionFormat,
395        NotableEventsConfig, PersistenceConfig, ProposedDimensionChange, ProposedRelationshipEvent,
396        Relationship, RelationshipConfig, RelationshipDimensionDefinition,
397        RelationshipDimensionsConfig, RelationshipEvaluation, RelationshipEvaluator,
398        RelationshipEvaluatorTrait, RelationshipEvent, RelationshipManager, RelationshipModel,
399        RelationshipPerspective, RelationshipSnapshot, RelationshipUpdate, format_relationship,
400        relationship_from_value, relationship_to_context_value, relationship_to_value,
401    };
402}
403
404pub mod observability {
405    pub use ai_agents_observability::{
406        AggregatedMetrics, AggregationConfig, AggregationDimension, BufferConfig, CostBreakdown,
407        CostConfig, CostEstimate, CostEstimator, CostSource, CostStats, EventStatus, EventType,
408        ExportConfig, ExportFormat, ExportResult, LanguageConfig, LatencyConfig, LatencyStats,
409        ModelPricing, ObservabilityConfig, ObservabilityHooks, ObservabilityManager,
410        ObservabilityReport, ObservationError, ObservationEvent, ObservationPurpose,
411        ObservationTokenUsage, ObservedLLMProvider, ObservedTool, PrivacyConfig, RawEventsFormat,
412        Redactor, ReportSummary, SpanContext, SpanGuard, TokenBreakdown, TokenConfig, TokenStats,
413        TokenUsageSource, UnknownPricePolicy, current_observation_context,
414        resolve_language_from_context, stable_hash, truncate_chars, with_observation_context,
415        with_observation_purpose, with_updated_observation_context,
416    };
417}
418
419pub mod reasoning {
420    pub use ai_agents_reasoning::{
421        CriterionResult, EvaluationResult, Plan, PlanAction, PlanAvailableActions,
422        PlanReflectionConfig, PlanStatus, PlanStep, PlanningConfig, ReasoningConfig,
423        ReasoningMetadata, ReasoningMode, ReasoningOutput, ReflectionAttempt, ReflectionConfig,
424        ReflectionMetadata, ReflectionMode, StepFailureAction, StepStatus, StringOrList,
425    };
426}
427
428pub mod disambiguation {
429    pub use ai_agents_disambiguation::{
430        AmbiguityAspect, AmbiguityDetectionResult, AmbiguityDetector, AmbiguityType, CacheConfig,
431        ClarificationConfig, ClarificationGenerator, ClarificationOption, ClarificationParseResult,
432        ClarificationQuestion, ClarificationStyle, ContextConfig, DetectionConfig,
433        DisambiguationConfig, DisambiguationContext, DisambiguationManager, DisambiguationResult,
434        MaxAttemptsAction, SkillDisambiguationOverride, SkipCondition, StateDisambiguationOverride,
435    };
436}
437
438pub mod tool_security {
439    pub use ai_agents_tools::{
440        CommandPolicyConfig, CommandRuleConfig, CommandTemplateConfig, DomainPolicyConfig,
441        MAX_TOOL_TIMEOUT_MS, NoWritePolicyBehavior, OperationPolicyConfig, PathPolicyConfig,
442        SecurityCheckResult, ToolPolicyConfig, ToolSecurityConfig, ToolSecurityEngine,
443    };
444}
445
446pub mod tools {
447    pub use ai_agents_core::{
448        CommandBindingKind, CommandPolicyBinding, DomainPolicyBinding, PathAccessMode,
449        PathBindingKind, PathPolicyBinding, PermissionOutcome, ResultLimitBinding, ResultLimitKind,
450        Tool, ToolActorContext, ToolApprovalRecord, ToolApprovalStatus, ToolCallClassification,
451        ToolCallSource, ToolCancellationToken, ToolExecutionContext, ToolExecutionLimits,
452        ToolExecutionRecord, ToolExecutionRequest, ToolInfo, ToolInvoker, ToolOperationKind,
453        ToolPolicyBindings, ToolPolicyDecisionRecord, ToolResult, ToolSafetyMetadata,
454        ToolSideEffectLevel,
455    };
456    pub use ai_agents_tools::{
457        AskUserTool, CalculatorTool, CommandRequest, CommandResponse, CommandRunner,
458        CommandRunnerSlot, CommandTool, ConditionEvaluator, CopyPathTool, DateTimeTool,
459        DeletePathTool, DiagnosticItem, DiagnosticSeverity, DiagnosticsProvider,
460        DiagnosticsProviderSlot, DiagnosticsRequest, DiagnosticsResponse, DiagnosticsTool,
461        EchoTool, EvaluationContext, FileEditTool, FileInfoTool, FileListTool, FileReadTool,
462        FileTool, FileVersionEvidence, FileVersionStore, FileWriteTool, GitDiffTool, GitStatusTool,
463        GlobTool, GrepTool, JsonTool, LLMGetter, MathTool, MovePathTool, PatchTool,
464        ProcessCommandRunner, ProviderHealth, QuestionHandler, QuestionHandlerSlot,
465        QuestionRequest, QuestionResponse, RandomTool, ResolvedTool, SimpleLLMGetter, SleepTool,
466        StaticCommandRunner, StaticDiagnosticsProvider, TemplateTool, TextTool, TodoItem,
467        TodoStatus, TodoStore, TodoTool, ToolAliases, ToolCallRecord, ToolContext, ToolDescriptor,
468        ToolError, ToolIdentity, ToolMetadata, ToolProvider, ToolProviderError, ToolProviderType,
469        ToolRegistry, ToolSchemaPromptMode, TrustLevel, UnavailableCommandRunner,
470        UnavailableDiagnosticsProvider, WebFetchTool, WebSearchProvider, WebSearchProviderSlot,
471        WebSearchRequest, WebSearchResponse, WebSearchResultItem, WebSearchSafeSearch,
472        WebSearchTool, create_builtin_registry, file_version_evidence,
473    };
474    pub use ai_agents_tools::{HttpTool, generate_schema};
475}
476
477/// MCP (Model Context Protocol) integration types.
478pub mod mcp {
479    pub use ai_agents_tools::mcp::{
480        MCPViewConfig, MCPViewTool, MCPWrapperConfig, MCPWrapperSecurity, MCPWrapperTool,
481        MCPWrapperTransport,
482    };
483}
484
485/// Dynamic agent spawning, registry, and inter-agent messaging.
486pub mod spawner {
487    pub use ai_agents_runtime::spawner::{
488        AgentRegistry, AgentSpawner, GenerateAgentTool, ListAgentsTool, NamespacedStorage,
489        RegistryHooks, RemoveAgentTool, ResolvedTemplate, SendMessageTool, SpawnedAgent,
490        SpawnedAgentInfo, auto_configure_spawner, configure_spawner_tools, resolve_templates,
491        spawner_from_config,
492    };
493}
494
495// Multi-agent orchestration patterns and tool wrappers.
496/// Key facts extraction and actor memory.
497pub mod facts {
498    pub use ai_agents_core::{SessionFilter, SessionMetadata, SessionSummary};
499    pub use ai_agents_facts::deduplicate_exact;
500    pub use ai_agents_facts::{
501        ActorMemoryConfig, CategoryDefinition, DedupConfig, DedupMethod, FactExtractor, FactStore,
502        FactsConfig, IdentificationConfig, IdentificationMethod, InjectionConfig, InjectionMode,
503        LLMFactExtractor, PrivacyConfig, SessionConfig,
504    };
505    pub use ai_agents_facts::{FactCategory, FactFilter, KeyFact};
506}
507
508pub mod eval {
509    pub use ai_agents_eval::*;
510}
511
512pub mod orchestration {
513    pub use ai_agents_runtime::orchestration::context::prepare_delegate_input;
514    pub use ai_agents_runtime::orchestration::tools::{
515        ConcurrentAskTool, GroupDiscussionTool, HandoffConversationTool, PipelineProcessTool,
516        RouteToAgentTool, configure_orchestration_tools,
517    };
518    pub use ai_agents_runtime::orchestration::types::{
519        AgentResult, ChatTurn, ConcurrentResult, GroupChatResult, HandoffEvent, HandoffResult,
520        PipelineResult, PipelineStage, RouteResult, RoutingMethod, StageOutput,
521    };
522    pub use ai_agents_runtime::orchestration::{concurrent, group_chat, handoff, pipeline, route};
523}
524
525// Top-level re-exports (legacy interface)
526pub use agent::{
527    Agent, AgentBuilder, AgentInfo, AgentResponse, AgentStreamEvent, AwaitBeforeNextTurn,
528    BackgroundOverflowPolicy, MainResponseDraft, MaintenanceMode, MaintenanceTaskPolicy,
529    ParallelToolsConfig, PostTurnOptimizationConfig, RuntimeAgent, RuntimeBranch,
530    RuntimeBranchOutcome, RuntimeBranchResult, RuntimeBranchStatus, RuntimeCommitBehavior,
531    RuntimeConfig, RuntimeOptimizationConfig, RuntimeOptimizationKind, RuntimeTaskPriority,
532    RuntimeTaskPurpose, ScheduledBranchSet, SkillCandidate, StreamBranchBuffer, StreamChunk,
533    StreamingConfig, StreamingDraftResult, StreamingOptimizationPolicy, TurnActorContext,
534    TurnBranchScheduler, TurnOptimizationContext,
535};
536pub use error::{AgentError, Result};
537pub use memory::{
538    CompactingMemory, CompactingMemoryConfig, CompressResult, CompressionEvent,
539    ConversationContext, EvictionReason, FactExtractedEvent, InMemoryStore, LLMSummarizer, Memory,
540    MemoryBudgetEvent, MemoryBudgetState, MemoryCompressEvent, MemoryEvictEvent, MemoryTokenBudget,
541    NoopSummarizer, OverflowStrategy, Summarizer, TokenAllocation, create_memory,
542    create_memory_from_config, create_memory_from_config_with_llm, estimate_message_tokens,
543    estimate_tokens,
544};
545pub use skill::{SkillDefinition, SkillExecutor, SkillLoader, SkillRef, SkillRouter, SkillStep};
546pub use spec::{
547    AgentSpec, FileStorageConfig, LLMConfig, LLMSelector, MemoryConfig, RedisStorageConfig,
548    RuntimeConfig as SpecRuntimeConfig, SqliteStorageConfig, StorageConfig, ToolAliasesConfig,
549    ToolConfig,
550};
551pub use template::TemplateLoader;
552pub use tools::HttpTool;
553pub use tools::{
554    CalculatorTool, DateTimeTool, EchoTool, FileTool, JsonTool, MathTool, RandomTool, TemplateTool,
555    TextTool, Tool, ToolRegistry, ToolResult, create_builtin_registry,
556};
557
558pub use llm::providers::{ProviderType, ProviderType as LLMProviderType, UnifiedLLMProvider};
559pub use llm::{
560    ChatMessage, LLMProvider, LLMRegistry, LLMResponse, LLMToolDefinition, LLMToolRequest,
561    MultiLLMRouter, Role, ToolChoice,
562};
563
564pub use process::{ProcessConfig, ProcessData, ProcessProcessor};
565pub use recovery::{
566    ByRoleFilter, ErrorRecoveryConfig, FilterConfig, KeepRecentFilter, MessageFilter,
567    RecoveryManager, SkipPatternFilter,
568};
569pub use tool_security::{
570    MAX_TOOL_TIMEOUT_MS, SecurityCheckResult, ToolPolicyConfig, ToolSecurityConfig,
571    ToolSecurityEngine,
572};
573
574pub use eval::{
575    EvalResult, EvalRunner, EvalRunnerOptions, EvalSettings, EvalSuite, ScenarioBudget,
576};
577pub use observability::{ObservabilityConfig, ObservabilityManager, ObservabilityReport};
578
579pub use context::{
580    BuiltinSource, ContextManager, ContextProvider, ContextSource, RefreshPolicy, TemplateRenderer,
581};
582#[cfg(feature = "sqlite")]
583pub use persistence::SqliteStorage;
584pub use persistence::{
585    AgentSnapshot, AgentStorage, FileStorage, MemorySnapshot, SessionInfo, SessionMetadata,
586    SessionOrderBy, SessionQuery, SpawnedAgentEntry, create_storage,
587};
588#[cfg(feature = "redis-storage")]
589pub use persistence::{RedisSessionMeta, RedisStorage};
590
591pub use state::{
592    CompareOp, ContextExtractor, ContextMatcher, GuardConditions, GuardOnlyEvaluator,
593    LLMTransitionEvaluator, PromptMode, StateAction, StateConfig, StateDefinition, StateMachine,
594    StateMachineSnapshot, StateMatcher, StateTransitionEvent, TimeMatcher, ToolCondition, ToolRef,
595    Transition, TransitionContext, TransitionEvaluator, TransitionGuard, TransitionTiming,
596};
597pub use tools::{
598    ConditionEvaluator, EvaluationContext, LLMGetter, SimpleLLMGetter, ToolCallRecord,
599};
600
601pub use hooks::{AgentHooks, CompositeHooks, HookTimer, LoggingHooks, NoopHooks};
602
603pub use hitl::{
604    ApprovalCondition, ApprovalHandler, ApprovalMessage, ApprovalRequest, ApprovalResolvedOutcome,
605    ApprovalResult, ApprovalTrigger, AutoApproveHandler, HITLCheckResult, HITLConfig, HITLEngine,
606    LlmGenerateConfig, LocalizedHandler, MessageLanguageConfig, MessageLanguageStrategy,
607    MessageResolver, RejectAllHandler, StateApprovalConfig, StateApprovalTrigger, TimeoutAction,
608    ToolApprovalConfig, create_handler, create_localized_handler, resolve_best_language,
609    resolve_tool_message,
610};
611
612// Tool Provider System (v0.5.1 - Simplified)
613pub use tools::{
614    ProviderHealth, ToolAliases, ToolContext, ToolDescriptor, ToolMetadata, ToolProvider,
615    ToolProviderError, ToolProviderType, TrustLevel,
616};
617
618// Reasoning & Reflection (v0.5.3)
619pub use reasoning::{
620    CriterionResult, EvaluationResult, Plan, PlanAction, PlanAvailableActions,
621    PlanReflectionConfig, PlanStatus, PlanStep, PlanningConfig, ReasoningConfig, ReasoningMetadata,
622    ReasoningMode, ReasoningOutput, ReflectionAttempt, ReflectionConfig, ReflectionMetadata,
623    ReflectionMode, StepFailureAction, StepStatus, StringOrList,
624};
625
626// Intent Disambiguation (v0.5.4)
627pub use disambiguation::{
628    AmbiguityAspect, AmbiguityDetectionResult, AmbiguityDetector, AmbiguityType, CacheConfig,
629    ClarificationConfig, ClarificationGenerator, ClarificationOption, ClarificationParseResult,
630    ClarificationQuestion, ClarificationStyle, ContextConfig, DetectionConfig,
631    DisambiguationConfig, DisambiguationContext, DisambiguationManager, DisambiguationResult,
632    MaxAttemptsAction, SkillDisambiguationOverride, SkipCondition, StateDisambiguationOverride,
633};
634
635#[cfg(test)]
636mod tests {
637    #[test]
638    fn test_facade_reexports_multi_llm_router() {
639        fn assert_type<T>() {}
640        assert_type::<crate::llm::MultiLLMRouter>();
641        assert_type::<crate::MultiLLMRouter>();
642    }
643
644    #[test]
645    fn test_facade_template_loader_rejects_nested_unknown_path() {
646        let directory = std::env::temp_dir().join(format!(
647            "ai-agents-facade-strict-template-{}",
648            std::process::id()
649        ));
650        std::fs::create_dir_all(&directory).unwrap();
651        std::fs::write(
652            directory.join("strict.yaml"),
653            r#"
654name: TestAgent
655system_prompt: test
656process:
657  inpt: []
658"#,
659        )
660        .unwrap();
661
662        let mut loader = crate::TemplateLoader::new();
663        loader.add_search_path(&directory);
664        let error = loader
665            .load_and_parse("strict.yaml")
666            .unwrap_err()
667            .to_string();
668        let _ = std::fs::remove_dir_all(&directory);
669        assert!(error.contains("process.inpt"), "{error}");
670    }
671
672    #[test]
673    fn test_facade_reexports_approval_resolved_outcome() {
674        fn assert_type<T>() {}
675        assert_type::<crate::hitl::ApprovalResolvedOutcome>();
676        assert_type::<crate::ApprovalResolvedOutcome>();
677    }
678}