# Copyright (c) Microsoft. All rights reserved.

"""Public API surface for Agent Framework core.

This module exposes the primary abstractions for agents, chat clients, tools, sessions,
middleware, observability, and workflows. Most public exports are resolved lazily to keep
``import agent_framework`` lightweight; importing a specific symbol still loads the module
that owns that symbol.
"""

from __future__ import annotations

# pyright: reportUnsupportedDunderAll=false
# ruff: noqa: F822
import importlib
import importlib.metadata
from collections.abc import Mapping
from typing import Any, Final

try:
    _version = importlib.metadata.version(__name__)
except importlib.metadata.PackageNotFoundError:
    _version = "0.0.0"  # Fallback for development mode
__version__: Final[str] = _version

from ._telemetry import (
    AGENT_FRAMEWORK_USER_AGENT,
    APP_INFO,
    USER_AGENT_KEY,
    USER_AGENT_TELEMETRY_DISABLED_ENV_VAR,
    prepend_agent_framework_to_user_agent,
)
from .exceptions import (
    AgentFrameworkException,
    MiddlewareException,
    UserInputRequiredException,
    WorkflowCheckpointException,
    WorkflowConvergenceException,
    WorkflowException,
    WorkflowRunnerException,
)

_LAZY_MODULE_EXPORTS: Final[Mapping[str, tuple[str, ...]]] = {
    "._agents": ("Agent", "BaseAgent", "RawAgent", "SupportsAgentRun"),
    "._clients": (
        "BaseChatClient",
        "BaseEmbeddingClient",
        "SupportsChatGetResponse",
        "SupportsCodeInterpreterTool",
        "SupportsFileSearchTool",
        "SupportsGetEmbeddings",
        "SupportsImageGenerationTool",
        "SupportsMCPTool",
        "SupportsShellTool",
        "SupportsWebSearchTool",
    ),
    "._compaction": (
        "COMPACTION_STATE_KEY",
        "EXCLUDE_REASON_KEY",
        "EXCLUDED_KEY",
        "GROUP_ANNOTATION_KEY",
        "GROUP_HAS_REASONING_KEY",
        "GROUP_ID_KEY",
        "GROUP_INDEX_KEY",
        "GROUP_KIND_KEY",
        "GROUP_TOKEN_COUNT_KEY",
        "SUMMARIZED_BY_SUMMARY_ID_KEY",
        "SUMMARY_OF_GROUP_IDS_KEY",
        "SUMMARY_OF_MESSAGE_IDS_KEY",
        "CharacterEstimatorTokenizer",
        "CompactionProvider",
        "CompactionStrategy",
        "ContextWindowCompactionStrategy",
        "SelectiveToolCallCompactionStrategy",
        "SlidingWindowStrategy",
        "SummarizationStrategy",
        "TokenBudgetComposedStrategy",
        "TokenizerProtocol",
        "ToolResultCompactionStrategy",
        "TruncationStrategy",
        "annotate_message_groups",
        "apply_compaction",
        "included_messages",
        "included_token_count",
    ),
    "._evaluation": (
        "AgentEvalConverter",
        "CheckResult",
        "ConversationSplit",
        "ConversationSplitter",
        "EvalItem",
        "EvalItemResult",
        "EvalNotPassedError",
        "EvalResults",
        "EvalScoreResult",
        "Evaluator",
        "ExpectedToolCall",
        "LocalEvaluator",
        "RubricScore",
        "evaluate_agent",
        "evaluate_workflow",
        "evaluator",
        "keyword_check",
        "tool_call_args_match",
        "tool_called_check",
        "tool_calls_present",
    ),
    "._feature_stage": ("ExperimentalFeature", "ReleaseCandidateFeature"),
    "._harness._agent": ("DEFAULT_HARNESS_INSTRUCTIONS", "create_harness_agent"),
    "._harness._background_agents": (
        "DEFAULT_BACKGROUND_AGENTS_SOURCE_ID",
        "BackgroundAgentsProvider",
        "BackgroundTaskInfo",
        "BackgroundTaskStatus",
    ),
    "._harness._file_access": (
        "DEFAULT_FILE_ACCESS_INSTRUCTIONS",
        "DEFAULT_FILE_ACCESS_SOURCE_ID",
        "AgentFileStore",
        "FileAccessProvider",
        "FileSearchMatch",
        "FileSearchResult",
        "FileStoreEntry",
        "FileSystemAgentFileStore",
        "InMemoryAgentFileStore",
    ),
    "._harness._file_memory": (
        "DEFAULT_FILE_MEMORY_INSTRUCTIONS",
        "DEFAULT_FILE_MEMORY_SOURCE_ID",
        "FileMemoryProvider",
    ),
    "._harness._loop": (
        "AgentLoopMiddleware",
        "JudgeVerdict",
        "background_tasks_running",
        "background_tasks_running_message",
        "todos_remaining",
        "todos_remaining_message",
    ),
    "._harness._memory": (
        "DEFAULT_MEMORY_SOURCE_ID",
        "MemoryContextProvider",
        "MemoryFileStore",
        "MemoryIndexEntry",
        "MemoryStore",
        "MemoryTopicRecord",
    ),
    "._harness._mode": ("DEFAULT_MODE_SOURCE_ID", "AgentModeProvider", "get_agent_mode", "set_agent_mode"),
    "._harness._todo": (
        "DEFAULT_TODO_SOURCE_ID",
        "TodoFileStore",
        "TodoInput",
        "TodoItem",
        "TodoProvider",
        "TodoSessionStore",
        "TodoStore",
    ),
    "._harness._tool_approval": (
        "DEFAULT_TOOL_APPROVAL_SOURCE_ID",
        "ToolApprovalMiddleware",
        "ToolApprovalRule",
        "ToolApprovalRuleCallback",
        "ToolApprovalState",
        "create_always_approve_tool_response",
        "create_always_approve_tool_with_arguments_response",
    ),
    "._mcp": (
        "MCPStdioTool",
        "MCPStreamableHTTPTool",
        "MCPTaskOptions",
        "MCPWebsocketTool",
        "SamplingApprovalCallback",
    ),
    "._middleware": (
        "AgentContext",
        "AgentMiddleware",
        "AgentMiddlewareLayer",
        "AgentMiddlewareTypes",
        "ChatAndFunctionMiddlewareTypes",
        "ChatContext",
        "ChatMiddleware",
        "ChatMiddlewareLayer",
        "ChatMiddlewareTypes",
        "FunctionInvocationContext",
        "FunctionMiddleware",
        "FunctionMiddlewareTypes",
        "MiddlewareTermination",
        "MiddlewareType",
        "MiddlewareTypes",
        "agent_middleware",
        "chat_middleware",
        "function_middleware",
    ),
    "._sessions": (
        "AgentSession",
        "ContextProvider",
        "FileHistoryProvider",
        "HistoryProvider",
        "InMemoryHistoryProvider",
        "MESSAGE_INJECTION_PENDING_MESSAGES_STATE_KEY",
        "MessageInjectionMiddleware",
        "ServiceSessionId",
        "SessionContext",
        "enqueue_messages",
        "register_state_type",
    ),
    "._settings": ("SecretString", "load_settings"),
    "._skills": (
        "AggregatingSkillsSource",
        "CachingSkillsSource",
        "ClassSkill",
        "DeduplicatingSkillsSource",
        "DelegatingSkillsSource",
        "FileSkill",
        "FileSkillScript",
        "FileSkillsSource",
        "FilteringSkillsSource",
        "InlineSkill",
        "InlineSkillResource",
        "InlineSkillScript",
        "InMemorySkillsSource",
        "MCPSkill",
        "MCPSkillResource",
        "MCPSkillsSource",
        "Skill",
        "SkillFrontmatter",
        "SkillResource",
        "SkillScript",
        "SkillScriptArgumentParser",
        "SkillScriptRunner",
        "SkillsProvider",
        "SkillsSource",
        "SkillsSourceContext",
    ),
    "._tools": (
        "SKIP_PARSING",
        "FunctionInvocationConfiguration",
        "FunctionInvocationLayer",
        "FunctionTool",
        "ToolTypes",
        "normalize_function_invocation_configuration",
        "tool",
    ),
    "._types": (
        "AgentResponse",
        "AgentResponseUpdate",
        "AgentRunInputs",
        "Annotation",
        "ChatOptions",
        "ChatResponse",
        "ChatResponseUpdate",
        "Content",
        "ContinuationToken",
        "Embedding",
        "EmbeddingGenerationOptions",
        "EmbeddingInputT",
        "EmbeddingT",
        "FinalT",
        "FinishReason",
        "FinishReasonLiteral",
        "GeneratedEmbeddings",
        "Message",
        "OuterFinalT",
        "OuterUpdateT",
        "ResponseStream",
        "Role",
        "RoleLiteral",
        "TextSpanRegion",
        "ToolMode",
        "UpdateT",
        "UsageDetails",
        "add_usage_details",
        "detect_media_type_from_base64",
        "map_chat_to_agent_update",
        "merge_chat_options",
        "normalize_messages",
        "normalize_tools",
        "prepend_instructions_to_messages",
        "validate_chat_options",
        "validate_tool_mode",
        "validate_tools",
    ),
    "._workflows._agent": ("WorkflowAgent",),
    "._workflows._agent_executor": ("AgentExecutor", "AgentExecutorRequest", "AgentExecutorResponse"),
    "._workflows._agent_utils": ("resolve_agent_id",),
    "._workflows._checkpoint": (
        "CheckpointID",
        "CheckpointStorage",
        "FileCheckpointStorage",
        "InMemoryCheckpointStorage",
        "WorkflowCheckpoint",
    ),
    "._workflows._const": ("DEFAULT_MAX_ITERATIONS",),
    "._workflows._edge": (
        "Case",
        "Default",
        "Edge",
        "EdgeCondition",
        "FanInEdgeGroup",
        "FanOutEdgeGroup",
        "SingleEdgeGroup",
        "SwitchCaseEdgeGroup",
        "SwitchCaseEdgeGroupCase",
        "SwitchCaseEdgeGroupDefault",
    ),
    "._workflows._edge_runner": ("create_edge_runner",),
    "._workflows._events": (
        "WorkflowErrorDetails",
        "WorkflowEvent",
        "WorkflowEventSource",
        "WorkflowEventType",
        "WorkflowRunState",
    ),
    "._workflows._executor": ("Executor", "handler"),
    "._workflows._function_executor": ("FunctionExecutor", "executor"),
    "._workflows._functional": (
        "FunctionalWorkflow",
        "FunctionalWorkflowAgent",
        "RunContext",
        "StepWrapper",
        "get_run_context",
        "step",
        "workflow",
    ),
    "._workflows._request_info_mixin": ("response_handler",),
    "._workflows._runner": ("Runner",),
    "._workflows._runner_context": ("InProcRunnerContext", "RunnerContext", "WorkflowMessage"),
    "._workflows._validation": (
        "EdgeDuplicationError",
        "GraphConnectivityError",
        "TypeCompatibilityError",
        "ValidationTypeEnum",
        "WorkflowValidationError",
        "validate_workflow_graph",
    ),
    "._workflows._viz": ("WorkflowViz",),
    "._workflows._workflow": ("Workflow", "WorkflowRunResult"),
    "._workflows._workflow_builder": ("WorkflowBuilder",),
    "._workflows._workflow_context": ("WorkflowContext",),
    "._workflows._workflow_executor": (
        "SubWorkflowRequestMessage",
        "SubWorkflowResponseMessage",
        "WorkflowExecutor",
    ),
}
_LAZY_EXPORTS: Final[dict[str, str]] = {
    name: module_name for module_name, names in _LAZY_MODULE_EXPORTS.items() for name in names
}

__all__ = [
    "AGENT_FRAMEWORK_USER_AGENT",
    "APP_INFO",
    "COMPACTION_STATE_KEY",
    "DEFAULT_BACKGROUND_AGENTS_SOURCE_ID",
    "DEFAULT_FILE_ACCESS_INSTRUCTIONS",
    "DEFAULT_FILE_ACCESS_SOURCE_ID",
    "DEFAULT_FILE_MEMORY_INSTRUCTIONS",
    "DEFAULT_FILE_MEMORY_SOURCE_ID",
    "DEFAULT_HARNESS_INSTRUCTIONS",
    "DEFAULT_MAX_ITERATIONS",
    "DEFAULT_MEMORY_SOURCE_ID",
    "DEFAULT_MODE_SOURCE_ID",
    "DEFAULT_TODO_SOURCE_ID",
    "DEFAULT_TOOL_APPROVAL_SOURCE_ID",
    "EXCLUDED_KEY",
    "EXCLUDE_REASON_KEY",
    "GROUP_ANNOTATION_KEY",
    "GROUP_HAS_REASONING_KEY",
    "GROUP_ID_KEY",
    "GROUP_INDEX_KEY",
    "GROUP_KIND_KEY",
    "GROUP_TOKEN_COUNT_KEY",
    "MESSAGE_INJECTION_PENDING_MESSAGES_STATE_KEY",
    "SKIP_PARSING",
    "SUMMARIZED_BY_SUMMARY_ID_KEY",
    "SUMMARY_OF_GROUP_IDS_KEY",
    "SUMMARY_OF_MESSAGE_IDS_KEY",
    "USER_AGENT_KEY",
    "USER_AGENT_TELEMETRY_DISABLED_ENV_VAR",
    "Agent",
    "AgentContext",
    "AgentEvalConverter",
    "AgentExecutor",
    "AgentExecutorRequest",
    "AgentExecutorResponse",
    "AgentFileStore",
    "AgentFrameworkException",
    "AgentLoopMiddleware",
    "AgentMiddleware",
    "AgentMiddlewareLayer",
    "AgentMiddlewareTypes",
    "AgentModeProvider",
    "AgentResponse",
    "AgentResponseUpdate",
    "AgentRunInputs",
    "AgentSession",
    "AggregatingSkillsSource",
    "Annotation",
    "BackgroundAgentsProvider",
    "BackgroundTaskInfo",
    "BackgroundTaskStatus",
    "BaseAgent",
    "BaseChatClient",
    "BaseEmbeddingClient",
    "CachingSkillsSource",
    "Case",
    "CharacterEstimatorTokenizer",
    "ChatAndFunctionMiddlewareTypes",
    "ChatContext",
    "ChatMiddleware",
    "ChatMiddlewareLayer",
    "ChatMiddlewareTypes",
    "ChatOptions",
    "ChatResponse",
    "ChatResponseUpdate",
    "CheckResult",
    "CheckpointID",
    "CheckpointStorage",
    "ClassSkill",
    "CompactionProvider",
    "CompactionStrategy",
    "Content",
    "ContextProvider",
    "ContextWindowCompactionStrategy",
    "ContinuationToken",
    "ConversationSplit",
    "ConversationSplitter",
    "DeduplicatingSkillsSource",
    "Default",
    "DelegatingSkillsSource",
    "Edge",
    "EdgeCondition",
    "EdgeDuplicationError",
    "Embedding",
    "EmbeddingGenerationOptions",
    "EmbeddingInputT",
    "EmbeddingT",
    "EvalItem",
    "EvalItemResult",
    "EvalNotPassedError",
    "EvalResults",
    "EvalScoreResult",
    "Evaluator",
    "Executor",
    "ExpectedToolCall",
    "ExperimentalFeature",
    "FanInEdgeGroup",
    "FanOutEdgeGroup",
    "FileAccessProvider",
    "FileCheckpointStorage",
    "FileHistoryProvider",
    "FileMemoryProvider",
    "FileSearchMatch",
    "FileSearchResult",
    "FileSkill",
    "FileSkillScript",
    "FileSkillsSource",
    "FileStoreEntry",
    "FileSystemAgentFileStore",
    "FilteringSkillsSource",
    "FinalT",
    "FinishReason",
    "FinishReasonLiteral",
    "FunctionExecutor",
    "FunctionInvocationConfiguration",
    "FunctionInvocationContext",
    "FunctionInvocationLayer",
    "FunctionMiddleware",
    "FunctionMiddlewareTypes",
    "FunctionTool",
    "FunctionalWorkflow",
    "FunctionalWorkflowAgent",
    "GeneratedEmbeddings",
    "GraphConnectivityError",
    "HistoryProvider",
    "InMemoryAgentFileStore",
    "InMemoryCheckpointStorage",
    "InMemoryHistoryProvider",
    "InMemorySkillsSource",
    "InProcRunnerContext",
    "InlineSkill",
    "InlineSkillResource",
    "InlineSkillScript",
    "JudgeVerdict",
    "LocalEvaluator",
    "MCPSkill",
    "MCPSkillResource",
    "MCPSkillsSource",
    "MCPStdioTool",
    "MCPStreamableHTTPTool",
    "MCPTaskOptions",
    "MCPWebsocketTool",
    "MemoryContextProvider",
    "MemoryFileStore",
    "MemoryIndexEntry",
    "MemoryStore",
    "MemoryTopicRecord",
    "Message",
    "MessageInjectionMiddleware",
    "MiddlewareException",
    "MiddlewareTermination",
    "MiddlewareType",
    "MiddlewareTypes",
    "OuterFinalT",
    "OuterUpdateT",
    "RawAgent",
    "ReleaseCandidateFeature",
    "ResponseStream",
    "Role",
    "RoleLiteral",
    "RubricScore",
    "RunContext",
    "Runner",
    "RunnerContext",
    "SamplingApprovalCallback",
    "SecretString",
    "SelectiveToolCallCompactionStrategy",
    "ServiceSessionId",
    "SessionContext",
    "SingleEdgeGroup",
    "Skill",
    "SkillFrontmatter",
    "SkillResource",
    "SkillScript",
    "SkillScriptArgumentParser",
    "SkillScriptRunner",
    "SkillsProvider",
    "SkillsSource",
    "SkillsSourceContext",
    "SlidingWindowStrategy",
    "StepWrapper",
    "SubWorkflowRequestMessage",
    "SubWorkflowResponseMessage",
    "SummarizationStrategy",
    "SupportsAgentRun",
    "SupportsChatGetResponse",
    "SupportsCodeInterpreterTool",
    "SupportsFileSearchTool",
    "SupportsGetEmbeddings",
    "SupportsImageGenerationTool",
    "SupportsMCPTool",
    "SupportsShellTool",
    "SupportsWebSearchTool",
    "SwitchCaseEdgeGroup",
    "SwitchCaseEdgeGroupCase",
    "SwitchCaseEdgeGroupDefault",
    "TextSpanRegion",
    "TodoFileStore",
    "TodoInput",
    "TodoItem",
    "TodoProvider",
    "TodoSessionStore",
    "TodoStore",
    "TokenBudgetComposedStrategy",
    "TokenizerProtocol",
    "ToolApprovalMiddleware",
    "ToolApprovalRule",
    "ToolApprovalRuleCallback",
    "ToolApprovalState",
    "ToolMode",
    "ToolResultCompactionStrategy",
    "ToolTypes",
    "TruncationStrategy",
    "TypeCompatibilityError",
    "UpdateT",
    "UsageDetails",
    "UserInputRequiredException",
    "ValidationTypeEnum",
    "Workflow",
    "WorkflowAgent",
    "WorkflowBuilder",
    "WorkflowCheckpoint",
    "WorkflowCheckpointException",
    "WorkflowContext",
    "WorkflowConvergenceException",
    "WorkflowErrorDetails",
    "WorkflowEvent",
    "WorkflowEventSource",
    "WorkflowEventType",
    "WorkflowException",
    "WorkflowExecutor",
    "WorkflowMessage",
    "WorkflowRunResult",
    "WorkflowRunState",
    "WorkflowRunnerException",
    "WorkflowValidationError",
    "WorkflowViz",
    "__version__",
    "add_usage_details",
    "agent_middleware",
    "annotate_message_groups",
    "apply_compaction",
    "background_tasks_running",
    "background_tasks_running_message",
    "chat_middleware",
    "create_always_approve_tool_response",
    "create_always_approve_tool_with_arguments_response",
    "create_edge_runner",
    "create_harness_agent",
    "detect_media_type_from_base64",
    "enqueue_messages",
    "evaluate_agent",
    "evaluate_workflow",
    "evaluator",
    "executor",
    "function_middleware",
    "get_agent_mode",
    "get_run_context",
    "handler",
    "included_messages",
    "included_token_count",
    "keyword_check",
    "load_settings",
    "map_chat_to_agent_update",
    "merge_chat_options",
    "normalize_function_invocation_configuration",
    "normalize_messages",
    "normalize_tools",
    "prepend_agent_framework_to_user_agent",
    "prepend_instructions_to_messages",
    "register_state_type",
    "resolve_agent_id",
    "response_handler",
    "set_agent_mode",
    "step",
    "todos_remaining",
    "todos_remaining_message",
    "tool",
    "tool_call_args_match",
    "tool_called_check",
    "tool_calls_present",
    "validate_chat_options",
    "validate_tool_mode",
    "validate_tools",
    "validate_workflow_graph",
    "workflow",
]


def __getattr__(name: str) -> Any:
    """Lazily resolve public names exported from ``agent_framework``."""
    if module_name := _LAZY_EXPORTS.get(name):
        value = getattr(importlib.import_module(module_name, __name__), name)
        globals()[name] = value
        return value

    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def __dir__() -> list[str]:
    """Return public names for interactive discovery."""
    return sorted(set(globals()) | set(__all__))
