# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Familiar Core v2.5.0 - Phase 4 Performance Optimization

The brain of the agent with full enterprise capabilities:
- LLM providers with intelligent routing
- Memory systems (simple + episodic)
- Tools and skills
- Security (trust, capabilities, budget)
- Observability (tracing, metrics, cost)
- Resilience (retry, circuit breaker)
- Distributed messaging (Redis bus)
- Workflow orchestration (sagas, DAGs)
- Evaluation framework (CI/CD testing)
- Experiments (A/B testing)
- Structured logging (JSON, context, filtering)

Phase 2.1 adds security hardening:
- ReDoS-resistant pattern matching (pattern_safety)
- Structured exception hierarchy (exceptions)
- Input sanitization (sanitization)
- Secret detection and masking (secrets_detection)
- Config validation with unknown key warnings

Phase 3 adds reliability & observability:
- Tool execution metrics (metrics)
- LLM call metrics with cost tracking
- Health check endpoints (health)
- Alert system with callbacks

Phase 4 adds performance optimization:
- LRU cache with TTL support (caching)
- Session cache with background persistence
- Pattern compilation cache
- Conversation history management
- Memoization decorator
"""

import logging

# =============================================================================
# CORE AGENT & CONFIG
# =============================================================================
from .agent import Agent, create_agent
from .config import Config, load_config, save_default_config

# =============================================================================
# MEMORY SYSTEMS
# =============================================================================
# Simple key-value memory (backwards compatible)
from .memory import ConversationHistory, Memory

# =============================================================================
# MODEL ROUTER (Intelligent Model Selection)
# =============================================================================
from .model_router import (
    MODEL_CAPABILITIES,  # noqa: F401
    MODEL_COSTS,  # noqa: F401
    ModelRouter,
    ModelStatus,
    QueryAnalyzer,
    QueryContext,
    QueryType,
    RoutingStrategy,
    create_router,
    create_standard_router,
    get_model_router,
    reset_model_router,  # noqa: F401
    set_model_router,  # noqa: F401
)

# =============================================================================
# LLM PROVIDERS
# =============================================================================
from .providers import (
    LLMResponse,
    StreamEvent,
    StreamEventType,
    ToolCall,
    get_available_providers,
    get_provider,
)

# =============================================================================
# SCHEDULER
# =============================================================================
from .scheduler import (  # noqa: F401
    Scheduler,
    TaskFrequency,
    TaskType,
    get_scheduler,
    reset_scheduler,
)

# =============================================================================
# MESH NETWORKING
# =============================================================================
# mesh exports: see comprehensive re-export block below (Phase 2.1+)
# =============================================================================
# SECURITY (Trust, Capabilities, Budget)
# =============================================================================
from .security import (
    CONFIRMATION_REQUIRED,
    SKILL_CAPABILITIES,
    TRUST_CAPABILITIES,
    Capability,
    SecureSession,
    SecurityConfig,
    SecurityMode,
    SessionManager,
    TrustLevel,
    check_skill_access,
    is_encryption_enabled,
)
from .skills import SkillLoader, create_skill_template

# =============================================================================
# TOOLS & SKILLS
# =============================================================================
from .tools import Tool, get_tool_registry, reset_tool_registry

# pattern_safety exports moved to Phase 2.1 comprehensive block below

# exceptions exports moved to Phase 2.1 comprehensive block below

# sanitization exports moved to Phase 2.1 comprehensive block below

# secrets_detection exports moved to Phase 2.1 comprehensive block below

# =============================================================================
# ENCRYPTION AT REST
# =============================================================================
try:
    from .encryption import (
        CRYPTOGRAPHY_AVAILABLE,
        EncryptedJSONStorage,
        EncryptedStorage,
        EncryptionConfig,
        EncryptionError,
        EncryptionKeyError,
    )
    from .encryption import (
        generate_key as generate_encryption_key,
    )
except ImportError:
    # Encryption module not available (missing cryptography package)
    EncryptedStorage = None
    EncryptedJSONStorage = None
    CRYPTOGRAPHY_AVAILABLE = False

# =============================================================================
# COMPLIANCE (HIPAA, SOC2, etc.)
# =============================================================================
try:
    from .compliance import (
        COMPLIANCE_PROFILES,
        ComplianceAuditLogger,
        ComplianceConfig,
        ComplianceMode,
        apply_compliance_profile,
        check_phi_content,
        get_compliance_config,
        validate_compliance,
    )

    COMPLIANCE_AVAILABLE = True
except ImportError:
    ComplianceMode = None
    COMPLIANCE_AVAILABLE = False

# =============================================================================
# RESILIENCE (Retry, Circuit Breaker)
# =============================================================================
from .constants import (  # noqa: F401
    VERSION,
    Channel,
    Limits,
    MemoryCategory,
    Provider,
    Role,
    ToolCategory,
)

# =============================================================================
# STRUCTURED LOGGING (Phase 5)
# =============================================================================
from .logging_config import (
    JSONFormatter,
    LogContext,
    LogMetrics,
    RequestLogger,
    SensitiveDataFilter,
    configure_logging,
    get_logger,
    log_context,
    with_request_id,
)
from .paths import (
    AGENT_DIR,
    CONFIG_FILE,  # noqa: F401
    DATA_DIR,
    HISTORY_FILE,  # noqa: F401
    MEMORY_FILE,  # noqa: F401
    SKILLS_DIR,
    ensure_core_dirs,  # noqa: F401
    ensure_dir,  # noqa: F401
)
from .resilience import (  # noqa: F811
    APIConnectionError,  # noqa: F401
    APITimeoutError,  # noqa: F401
    CircuitBreaker,
    CircuitBreakerConfig,  # noqa: F401
    CircuitBreakerError,
    CircuitState,  # noqa: F401
    RetryableError,  # RateLimitError: see exceptions block
    RetryableOperation,  # noqa: F401
    RetryConfig,
    classify_exception,  # noqa: F401
    get_all_circuit_status,  # noqa: F401
    get_circuit_breaker,
    reset_circuit_breaker,
    retry_on_rate_limit,
    with_retry,
)
from .result import Err, Ok, Result
from .skill_data import load_skill_data, save_skill_data, skill_data

# =============================================================================
# STRUCTURED OUTPUTS (Pydantic Parsing — base utilities)
# Note: extract_json is re-exported from structured_output module below
# =============================================================================
from .structured import (
    ClassificationOutput,  # noqa: F401
    ExtractionOutput,  # noqa: F401
    ParseResult,
    PlanOutput,
    PlanStep,
    ReflectionOutput,
    SentimentOutput,  # noqa: F401
    ToolCallOutput,
    create_json_prompt,
    parse_json,
    parse_plan,
    parse_reflection,
    parse_tool_response,  # noqa: F401
    schema_to_prompt,
)

# =============================================================================
# UTILITIES
# =============================================================================
from .utils import atomic_write_json

# =============================================================================
# VERSION
# =============================================================================
__version__ = "1.10.0"

# =============================================================================
# MCP (Model Context Protocol) INTEGRATION
# =============================================================================
from .mcp import (
    MCPClient,
    MCPClientError,
    MCPConfig,
    MCPConnectionError,
    MCPManager,
    MCPServerConfig,
    MCPToolBridge,
    MCPTransport,
    mcp_tool_to_familiar,
)

# =============================================================================
# PHASE 4 ENTERPRISE MODULES (lazy imports to avoid dependency issues)
# =============================================================================


def _lazy_import_phase4():
    """Import Phase 4 enterprise modules on demand."""
    pass


# These are available but may require additional dependencies:
# - model_router: Intelligent model selection
# - episodic_memory: Advanced memory with semantic retrieval
# - observability: Enhanced tracing with OTLP export
# - guardrails: Cost and safety limits
# - context: Context compilation (Google ADK pattern)
# - bus: Inter-skill communication
# - distributed: Redis-backed distributed bus
# - saga: Distributed transactions with compensation
# - orchestration: Workflow DAG execution
# - persistence: Durable state storage
# - streaming_executor: Async streaming execution
# - evaluation: Golden test framework
# - ci_eval: CI/CD evaluation pipeline
# - experiments: A/B testing framework
# - tool_registry: Enhanced tool management
# - structured_output: Enhanced Pydantic parsing

__all__ = [
    # Version
    "__version__",
    # Config & Agent
    "Config",
    "load_config",
    "save_default_config",
    "Agent",
    "create_agent",
    # Providers
    "get_provider",
    "get_available_providers",
    "StreamEvent",
    "StreamEventType",
    "LLMResponse",
    "ToolCall",
    # Model Router
    "ModelRouter",
    "QueryContext",
    "QueryAnalyzer",
    "RoutingStrategy",
    "ModelStatus",
    "QueryType",
    "get_model_router",
    "create_router",
    "create_standard_router",
    # Memory
    "Memory",
    "ConversationHistory",
    # Tools & Skills
    "Tool",
    "get_tool_registry",
    "reset_tool_registry",
    "SkillLoader",
    "create_skill_template",
    # Scheduler
    "Scheduler",
    "get_scheduler",
    "TaskFrequency",
    "TaskType",
    # Mesh
    "MeshGateway",
    "MeshNode",
    "MeshConfig",
    "Message",
    # Security
    "TrustLevel",
    "Capability",
    "SecurityMode",
    "SecureSession",
    "SessionManager",
    "SecurityConfig",
    "check_skill_access",
    "is_encryption_enabled",
    "TRUST_CAPABILITIES",
    "CONFIRMATION_REQUIRED",
    "SKILL_CAPABILITIES",
    # Pattern Safety
    "safe_search",
    "safe_match_any",
    "check_shell_safety",
    "check_prompt_injection",
    "sanitize_tool_output",
    "DANGEROUS_SHELL_PATTERNS",
    "PROMPT_INJECTION_PATTERNS",
    # Exceptions
    "FamiliarError",
    "ConfigurationError",
    "SecurityError",
    "AuthenticationError",
    "AuthorizationError",
    "RateLimitError",
    "BudgetExceededError",
    "InputValidationError",
    "ProviderError",
    "ProviderConnectionError",
    "ProviderRateLimitError",
    "ToolError",
    "ToolNotFoundError",
    "ToolExecutionError",
    "SessionError",
    "SessionValidationError",
    "ValidationError",
    # Sanitization
    "SanitizationLevel",
    "SanitizationResult",
    "sanitize_user_input",
    "sanitize_for_shell",
    "sanitize_for_path",
    "sanitize_for_logging",
    # Secrets Detection
    "SecretType",
    "SecretFinding",
    "detect_secrets",
    "mask_secrets",
    "safe_log",
    "audit_for_secrets",
    # Encryption
    "EncryptedStorage",
    "EncryptedJSONStorage",
    "EncryptionConfig",
    "EncryptionError",
    "EncryptionKeyError",
    "generate_encryption_key",
    "CRYPTOGRAPHY_AVAILABLE",
    # Compliance
    "ComplianceMode",
    "ComplianceConfig",
    "apply_compliance_profile",
    "validate_compliance",
    "get_compliance_config",
    "check_phi_content",
    "ComplianceAuditLogger",
    "COMPLIANCE_PROFILES",
    "COMPLIANCE_AVAILABLE",
    # Resilience
    "RetryConfig",
    "with_retry",
    "retry_on_rate_limit",
    "CircuitBreaker",
    "CircuitBreakerError",
    "get_circuit_breaker",
    "reset_circuit_breaker",
    "RetryableError",
    "RateLimitError",
    # Structured Outputs
    "parse_json",
    "extract_json",
    "ParseResult",
    "PlanOutput",
    "PlanStep",
    "ReflectionOutput",
    "ToolCallOutput",
    "parse_plan",
    "parse_reflection",
    "schema_to_prompt",
    "create_json_prompt",
    # MCP (Model Context Protocol)
    "MCPConfig",
    "MCPServerConfig",
    "MCPTransport",
    "MCPClient",
    "MCPClientError",
    "MCPConnectionError",
    "MCPManager",
    "MCPToolBridge",
    "mcp_tool_to_familiar",
    # Structured Logging (Phase 5)
    "configure_logging",
    "get_logger",
    "JSONFormatter",
    "SensitiveDataFilter",
    "LogContext",
    "log_context",
    "with_request_id",
    "LogMetrics",
    "RequestLogger",
    # User Management (Phase 1 - v1.6)
    "UserManager",
    "User",
    "UserRole",
    "UserStatus",
    "UserContext",
    "get_user_manager",
    "setup_first_admin",
    # Data Isolation (Phase 1 - v1.6)
    "DataStore",
    "DataScope",
    "DataCategory",
    "get_data_store",
    "get_data_store_from_context",
    # Utilities
    "atomic_write_json",
    "load_skill_data",
    "save_skill_data",
    "skill_data",
    "DATA_DIR",
    "AGENT_DIR",
    "SKILLS_DIR",
    "Role",
    "Channel",
    "Provider",
    "Limits",
    "VERSION",
    "Result",
    "Ok",
    "Err",
]

logger = logging.getLogger(__name__)

# =============================================================================
# USER MANAGEMENT (Phase 1 - v1.6)
# =============================================================================
try:
    from .users import (
        User,
        UserContext,
        UserManager,
        UserRole,
        UserStatus,
        get_user_manager,
        setup_first_admin,
    )
except ImportError as e:
    logger.debug("Optional dependency not available: %s", e)
# =============================================================================
# DATA ISOLATION (Phase 1 - v1.6)
# =============================================================================
try:
    from .data_store import (
        DataCategory,
        DataScope,
        DataStore,
        get_data_store,
        get_data_store_from_context,
    )
except ImportError as e:
    logger.debug("Optional dependency not available: %s", e)
# =============================================================================
# ANALYTICS (Phase 2 - v1.7)
# =============================================================================
try:
    from .analytics import (
        AggregationPeriod,  # noqa: F401
        AnalyticsStore,  # noqa: F401
        BudgetAlert,  # noqa: F401
        EventType,  # noqa: F401
        UsageEvent,  # noqa: F401
        UsageSummary,  # noqa: F401
        get_analytics_store,  # noqa: F401
        record_agent_usage,  # noqa: F401
    )

    ANALYTICS_AVAILABLE = True
except ImportError:
    ANALYTICS_AVAILABLE = False

# =============================================================================
# SSO AUTHENTICATION (Phase 2 - v1.7)
# =============================================================================
try:
    from .auth import (
        SSOClient,  # noqa: F401
        SSOConfig,  # noqa: F401
        SSOProvider,  # noqa: F401
        SSOTokens,  # noqa: F401
        SSOUser,  # noqa: F401
        create_sso_client,  # noqa: F401
        get_sso_provider_name,  # noqa: F401
        setup_sso_routes,  # noqa: F401
    )

    SSO_AVAILABLE = True
except ImportError:
    SSO_AVAILABLE = False

# =============================================================================
# HIGH AVAILABILITY (Phase 4 - v2.0)
# =============================================================================
try:
    from .ha import (  # noqa: F811 - HA HealthChecker/HealthStatus superseded by standalone health module
        HAConfig,  # noqa: F401
        HAManager,  # NodeInfo: see mesh module  # noqa: F401
        HAMode,  # noqa: F401
        NodeState,  # noqa: F401
        # HealthChecker, HealthStatus: see standalone health module below
        RedisSessionStore,  # noqa: F401
        SystemdWatchdog,  # noqa: F401
        get_ha_manager,  # get_health_checker: see health module  # noqa: F401
        init_ha,  # noqa: F401
        setup_ha_routes,  # noqa: F401
        shutdown_ha,  # noqa: F401
    )

    HA_AVAILABLE = True
except ImportError:
    HA_AVAILABLE = False

# =============================================================================
# AUDIT LOGGING (Phase 4 - v2.0)
# =============================================================================
try:
    from .audit import (
        AuditAction,  # noqa: F401
        AuditConfig,  # noqa: F401
        AuditEvent,  # noqa: F401
        AuditSeverity,  # noqa: F401
        AuditStore,  # noqa: F401
        audit_log,  # noqa: F401
        get_audit_store,  # noqa: F401
        setup_audit_routes,  # noqa: F401
    )

    AUDIT_AVAILABLE = True
except ImportError:
    AUDIT_AVAILABLE = False

# =============================================================================
# BACKUP & RESTORE (Phase 4 - v2.0)
# =============================================================================
try:
    from .backup import (
        BackupConfig,  # noqa: F401
        BackupManager,  # noqa: F401
        BackupManifest,  # noqa: F401
        BackupStatus,  # noqa: F401
        BackupType,  # noqa: F401
    )

    BACKUP_AVAILABLE = True
except ImportError:
    BACKUP_AVAILABLE = False

# =============================================================================
# PHASE 2.1 - SECURITY HARDENING (v2.1)
# =============================================================================

# Pattern Safety - ReDoS-resistant regex matching (re-export; supersedes partial earlier import)
# Structured Exceptions (comprehensive re-export; supersedes earlier partial imports)
from .exceptions import (  # noqa: F811, E402
    AuthenticationError,
    AuthorizationError,
    BudgetExceededError,
    ConfigurationError,
    FamiliarError,
    InputValidationError,
    ProviderAuthenticationError,  # noqa: F401
    ProviderConfigError,  # noqa: F401
    ProviderConnectionError,
    ProviderContentFilterError,  # noqa: F401
    ProviderError,
    ProviderRateLimitError,
    ProviderResponseError,  # noqa: F401
    RateLimitError,
    SecurityError,
    SessionCorruptedError,  # noqa: F401
    SessionError,
    SessionExpiredError,  # noqa: F401
    SessionValidationError,
    SkillConfigError,  # noqa: F401
    ToolError,
    ToolExecutionError,
    ToolNotFoundError,
    ToolPermissionError,  # noqa: F401
    ToolTimeoutError,  # noqa: F401
    ValidationError,
)

# Health Checks
from .health import (  # noqa: E402
    DependencyHealth,  # noqa: F401
    DependencyType,  # noqa: F401
    HealthChecker,  # noqa: F401
    HealthCheckResult,  # noqa: F401
    HealthStatus,  # noqa: F401
    ResourceHealth,  # noqa: F401
    check_health,  # noqa: F401
    get_health_checker,  # noqa: F401
    liveness,  # noqa: F401
    readiness,  # noqa: F401
    register_dependency_check,  # noqa: F401
    reset_health_checker,  # noqa: F401
    startup,  # noqa: F401
)

# =============================================================================
# PHASE 3 - RELIABILITY & OBSERVABILITY (v2.1)
# =============================================================================
# Metrics Collection
from .metrics import (  # noqa: E402
    AlertSeverity,  # noqa: F401
    LLMCallRecord,  # noqa: F401
    LLMMetrics,  # noqa: F401
    MetricAlert,  # noqa: F401
    MetricsCollector,  # noqa: F401
    MetricType,  # noqa: F401
    ToolExecutionRecord,  # noqa: F401
    ToolMetrics,  # noqa: F401
    get_metrics_collector,  # noqa: F401
    record_llm_call,  # noqa: F401
    record_tool_execution,  # noqa: F401
    reset_metrics_collector,  # noqa: F401
)
from .pattern_safety import (  # noqa: F811, E402
    DANGEROUS_SHELL_PATTERNS,
    PATH_TRAVERSAL_PATTERNS,  # noqa: F401
    PROMPT_INJECTION_PATTERNS,
    SENSITIVE_DATA_PATTERNS,  # noqa: F401
    check_prompt_injection,
    check_shell_safety,
    safe_match_any,
    safe_search,
    sanitize_tool_output,
)

# Input Sanitization
from .sanitization import (  # noqa: F811, E402
    SanitizationLevel,
    SanitizationResult,
    sanitize_for_logging,
    sanitize_for_path,
    sanitize_for_shell,
    sanitize_user_input,
    strip_ansi_codes,  # noqa: F401
)

# Secret Detection
from .secrets_detection import (  # noqa: F811, E402
    SECRET_PATTERNS,  # noqa: F401
    SecretFinding,
    SecretsAuditResult,  # noqa: F401
    SecretType,
    audit_for_secrets,
    detect_secrets,
    mask_secrets,
    mask_secrets_with_hash,  # noqa: F401
    safe_log,
)

# =============================================================================
# CONSTITUTIONAL PERSONALITY (Phase 1 - Hospitality Constitution)
# =============================================================================
try:
    from .constitution import (
        STAGE_THRESHOLDS,  # noqa: F401
        ChannelPersonality,  # noqa: F401
        ConstitutionalIdentity,  # noqa: F401
        InteractionTracker,  # noqa: F401
        RelationshipStage,  # noqa: F401
        get_constitutional_preset,  # noqa: F401
        get_constitutional_prompt,  # noqa: F401
        get_relationship_stage,  # noqa: F401
    )

    CONSTITUTION_AVAILABLE = True
except ImportError:
    CONSTITUTION_AVAILABLE = False

# =============================================================================
# PHASE 4 - PERFORMANCE OPTIMIZATION (v2.1)
# =============================================================================

# Caching
# SkillBus — inter-skill pub/sub, invocation, dead-letter queue, shared state, workflows
from .bus import (  # noqa: E402
    DEFAULT_RETRY_POLICY,  # noqa: F401
    NO_RETRY_POLICY,  # noqa: F401
    DeadLetter,  # noqa: F401
    DeadLetterQueue,  # noqa: F401
    SharedState,  # noqa: F401
    SkillBus,  # noqa: F401
    SkillEndpoint,  # noqa: F401
    WorkflowStepStatus,  # noqa: F401
    get_skill_bus,  # noqa: F401
    invoke,  # noqa: F401
    invoke_no_retry,  # noqa: F401
    publish,  # noqa: F401
    set_skill_bus,  # noqa: F401
    skill_action,  # noqa: F401
    subscribe,  # noqa: F401
)
from .bus import (  # noqa: E402
    Message as BusMessage,  # noqa: F401
)
from .bus import (  # noqa: E402
    MessageType as BusMessageType,  # noqa: F401
)
from .bus import (  # noqa: E402
    Priority as BusPriority,  # noqa: F401
)
from .bus import (  # noqa: E402
    RetryPolicy as BusRetryPolicy,  # noqa: F401
)
from .bus import (  # noqa: E402
    RetryStrategy as BusRetryStrategy,  # noqa: F401
)
from .bus import (  # noqa: E402
    Workflow as BusWorkflow,  # noqa: F401
)
from .bus import (  # noqa: E402
    WorkflowStep as BusWorkflowStep,  # noqa: F401
)
from .caching import (  # noqa: E402
    CachedSession,  # noqa: F401
    ConversationHistoryManager,  # noqa: F401
    LRUCache,  # noqa: F401
    PatternCache,  # noqa: F401
    SessionCache,  # noqa: F401
    get_history_manager,  # noqa: F401
    get_pattern_cache,  # noqa: F401
    get_session_cache,  # noqa: F401
    memoize,  # noqa: F401
    reset_caches,  # noqa: F401
)

# Context / RAG — chunked document retrieval pipeline
from .context import (  # noqa: E402
    ChromaVectorStore,  # noqa: F401
    ContextCompiler,  # noqa: F401
    ContextConfig,  # noqa: F401
    InMemoryVectorStore,  # noqa: F401
    RetrievalConfig,  # noqa: F401
    SemanticRetriever,  # noqa: F401
    TokenCounter,  # noqa: F401
    WorkingContext,  # noqa: F401
    get_semantic_retriever,  # noqa: F401
    get_token_counter,  # noqa: F401
    set_semantic_retriever,  # noqa: F401
)
from .context import (  # noqa: E402
    Document as RAGDocument,  # noqa: F401
)

# Embeddings — semantic vector search
from .embeddings import (  # noqa: E402
    EmbeddingProvider,  # noqa: F401
    HTTPEmbeddings,  # noqa: F401
    OllamaEmbeddings,  # noqa: F401
    ONNXEmbeddings,  # noqa: F401
    OpenAIEmbeddings,  # noqa: F401
    TFIDFEmbeddings,  # noqa: F401
    VoyageEmbeddings,  # noqa: F401
    cosine_similarity,  # noqa: F401
    get_embedding_provider,  # noqa: F401
    top_k_similar,  # noqa: F401
)

# Experiment Framework — feature flags and A/B testing
from .experiments import (  # noqa: E402
    Experiment,  # noqa: F401
    ExperimentManager,  # noqa: F401
    ExperimentResults,  # noqa: F401
    ExperimentStatus,  # noqa: F401
    FeatureFlag,  # noqa: F401
    FlagStatus,  # noqa: F401
    Variant,  # noqa: F401
    get_experiment_manager,  # noqa: F401
    get_variant,  # noqa: F401
    is_enabled,  # noqa: F401
    set_experiment_manager,  # noqa: F401
    track_conversion,  # noqa: F401
    track_metric,  # noqa: F401
)

# Mesh Network — P2P agent networking (Phase 1-4: discovery, trust, memory, delegation)
from .mesh import (  # noqa: E402
    DiscoveredPeer,  # noqa: F401
    MemoryBridge,  # noqa: F401
    MeshConfig,
    MeshDiscovery,  # noqa: F401
    MeshGateway,
    MeshNode,
    MeshSkillEndpoint,  # noqa: F401
    MeshTrustManager,  # noqa: F401
    Message,
    MsgType,  # noqa: F401
    NodeInfo,  # noqa: F401
    PeerStore,  # noqa: F401
    PermissionMatrix,  # noqa: F401
    RemoteAgent,  # noqa: F401
    SharedMemoryStore,  # noqa: F401
    TrustRecord,  # noqa: F401
    TrustStore,  # noqa: F401
    generate_connection_string,  # noqa: F401
    get_mesh_config,  # noqa: F401
    run_gateway,  # noqa: F401
    run_node,  # noqa: F401
)

# Multi-agent Orchestration
from .orchestration import (  # noqa: E402
    AgentBase,  # noqa: F401
    AgentRegistry,  # noqa: F401
    AgentRole,  # noqa: F401
    AgentStatus,  # noqa: F401
    FunctionAgent,  # noqa: F401
    LLMAgent,  # noqa: F401
    OrchestrationStrategy,  # noqa: F401
    Orchestrator,  # noqa: F401
    Task,  # noqa: F401
    TaskResult,  # noqa: F401
)

# Progressive Capability Disclosure
from .progressive import (  # noqa: E402
    DISCOVERABLE_SKILLS,  # noqa: F401
    MILESTONES,  # noqa: F401
    STARTER_SKILLS,  # noqa: F401
    SkillUsageTracker,  # noqa: F401
    check_milestone,  # noqa: F401
    filter_starter_skills,  # noqa: F401
    generate_weekly_digest,  # noqa: F401
    on_interaction_complete,  # noqa: F401
    on_tool_executed,  # noqa: F401
    on_tool_not_found,  # noqa: F401
    suggest_skill_for_tool,  # noqa: F401
)

# Saga Pattern — multi-step atomic workflows with automatic compensation
from .saga import (  # noqa: E402
    CompensationStrategy,  # noqa: F401
    FileSagaLog,  # noqa: F401
    InMemorySagaLog,  # noqa: F401
    Saga,  # noqa: F401
    SagaBuilder,  # noqa: F401
    SagaExecution,  # noqa: F401
    SagaOrchestrator,  # noqa: F401
    SagaStatus,  # noqa: F401
    SagaStep,  # noqa: F401
    StepStatus,  # noqa: F401
    compensates,  # noqa: F401
    get_saga_orchestrator,  # noqa: F401
    saga_step,  # noqa: F401
    set_saga_orchestrator,  # noqa: F401
)

# Structured Outputs — guaranteed schema-compliant LLM responses
from .structured_output import (  # noqa: E402
    PYDANTIC_AVAILABLE,  # noqa: F401
    ExtractionError,  # noqa: F401
    ExtractionMethod,  # noqa: F401
    GenerationResult,  # noqa: F401
    MaxRetriesExceeded,  # noqa: F401
    OutputFormat,  # noqa: F401
    OutputSchema,  # noqa: F401
    SchemaValidationError,  # noqa: F401
    StructuredGenerator,  # noqa: F401
    StructuredOutputError,  # noqa: F401
    ValidationStrategy,  # noqa: F401
    build_structured_prompt,  # noqa: F401
    extract_json,
    get_json_schema,  # noqa: F401
    repair_json,  # noqa: F401
    validate_against_schema,  # noqa: F401
)
