# LLM Summary Detail File

This file is a concatenation of all individual *llm.txt files found in the directory tree. Each section below corresponds to a specific directory's summary file.

================================================================================

## Section 1: agent/adk/adk_llm.txt

**Source file:** `agent/adk/adk_llm.txt`

Here is the comprehensive developer guide for the `adk` directory.

## Quick Summary
The `adk` directory serves as the core integration layer between the Solace AI Connector framework and Google's Agent Development Kit (ADK). It provides the essential components for building, configuring, and running sophisticated AI agents within a Solace messaging environment.

The architecture is designed for modularity and extensibility. The `setup.py` module acts as the main configuration hub, using factory functions from `services.py` to initialize pluggable services (like `FilesystemArtifactService` for artifact storage) and loading tools (Python functions, MCP tools) via the `ADKToolWrapper`.

Once initialized, the `AppLlmAgent` (a custom agent class) is managed by the `runner.py` module, which handles the asynchronous task execution loop. The agent's behavior is dynamically augmented at runtime by a rich set of callbacks from `callbacks.py`. These callbacks inject dynamic instructions, manage large tool responses, log events to Solace, and handle advanced features like streaming artifact creation and auto-continuation of conversations. The `models/` subdirectory provides the concrete LLM clients, with `LiteLlm` offering broad compatibility with various model providers.

## Files and Subdirectories Overview
- **Direct files:**
  - `__init__.py`: Standard Python package initializer.
  - `app_llm_agent.py`: Defines a custom `LlmAgent` subclass that holds a reference to its host component.
  - `callbacks.py`: Provides a rich set of ADK callback functions for dynamic instructions, metadata injection, and Solace integration.
  - `filesystem_artifact_service.py`: A local filesystem-based implementation of ADK's `BaseArtifactService`.
  - `invocation_monitor.py`: A utility for monitoring and logging agent invocations to YAML files for debugging.
  - `runner.py`: Manages the asynchronous execution of ADK agent tasks, including cancellation support.
  - `services.py`: Contains factory functions for initializing ADK services (session, artifact, memory) based on configuration.
  - `setup.py`: Handles the high-level initialization of the ADK agent, tools, and runner.
  - `stream_parser.py`: An internal utility for parsing fenced artifact blocks from an LLM's streaming response.
  - `tool_wrapper.py`: A wrapper for Python functions to make them compatible with ADK, handling embed resolution and config injection.
- **Subdirectories:**
  - `models/`: Contains concrete `BaseLlm` implementations for interfacing with various LLM providers.

## Developer API Reference

### Direct Files

#### app_llm_agent.py
**Purpose:** A custom `LlmAgent` subclass that includes a reference to its hosting component, allowing callbacks and tools to access host-level configurations and services.
**Import:** `from agent.adk.app_llm_agent import AppLlmAgent`

**Classes/Functions/Constants:**
- `AppLlmAgent(host_component: Any = None, **kwargs)`: A custom `LlmAgent` that can be linked to a host component. The `host_component` is set post-initialization and is excluded from serialization.

#### callbacks.py
**Purpose:** Provides a suite of ADK callback functions that hook into the agent's lifecycle to inject custom logic. These are typically not called directly but are assigned to the agent during setup.
**Import:** `from agent.adk import callbacks`

**Classes/Functions/Constants:**
- `inject_dynamic_instructions_callback(...)`: Injects instructions into the prompt based on host configuration, active tools, and peer agents.
- `manage_large_mcp_tool_responses_callback(...)`: Intercepts large tool responses, saves them as artifacts, and returns a truncated summary to the LLM.
- `after_tool_callback_inject_metadata(...)`: After a tool creates an artifact, this loads its metadata and injects it into the tool response.
- `process_artifact_blocks_callback(...)`: Processes streaming text to identify and save fenced artifact blocks (e.g., `«««save_artifact:...»»»`).
- `auto_continue_on_max_tokens_callback(...)`: Automatically continues a conversation if the LLM response was interrupted due to token limits.
- `notify_tool_invocation_start_callback(...)`: Sends a status update over Solace when a tool is about to be invoked.
- `solace_llm_invocation_callback(...)`: Sends a status update over Solace when the agent calls the LLM.

#### filesystem_artifact_service.py
**Purpose:** An implementation of `BaseArtifactService` that stores artifacts on the local filesystem, organized by scope, user, and session.
**Import:** `from agent.adk.filesystem_artifact_service import FilesystemArtifactService`

**Classes/Functions/Constants:**
- `FilesystemArtifactService(base_path: str, scope_identifier: str)`: A service for managing artifacts on the local disk.
  - `async save_artifact(...) -> int`: Saves an artifact and returns its version number.
  - `async load_artifact(...) -> Optional[adk_types.Part]`: Loads a specific version of an artifact, or the latest if unspecified.
  - `async list_artifact_keys(...) -> List[str]`: Lists the names of all artifacts for a given user/session.
  - `async delete_artifact(...)`: Deletes an artifact and all its versions.

#### invocation_monitor.py
**Purpose:** A debugging utility that logs the entire lifecycle of an agent invocation, from the initial request to the final response, into a structured YAML file.
**Import:** `from agent.adk.invocation_monitor import InvocationMonitor`

**Classes/Functions/Constants:**
- `InvocationMonitor()`: A class that monitors and logs agent message flows.
  - `log_message_event(direction: str, topic: str, payload: any, ...)`: Logs a single message event. The monitor automatically starts and stops logging based on topic patterns.
  - `cleanup()`: Finalizes any active logging sessions.

#### runner.py
**Purpose:** Provides the core asynchronous task execution logic for the ADK agent, including robust cancellation handling.
**Import:** `from agent.adk.runner import run_adk_async_task_thread_wrapper, TaskCancelledError`

**Classes/Functions/Constants:**
- `run_adk_async_task_thread_wrapper(component, adk_session, adk_content, ...)`: A high-level wrapper that runs an ADK task in a separate thread and handles all cleanup and error finalization.
- `TaskCancelledError(Exception)`: Custom exception raised when an agent task is cancelled externally.

#### services.py
**Purpose:** Provides factory functions to initialize the various ADK services based on the agent's configuration file.
**Import:** `from agent.adk.services import initialize_session_service, initialize_artifact_service, initialize_memory_service`

**Classes/Functions/Constants:**
- `initialize_session_service(component) -> BaseSessionService`: Creates a session service (e.g., `InMemorySessionService`).
- `initialize_artifact_service(component) -> BaseArtifactService`: Creates an artifact service (e.g., `FilesystemArtifactService`, `GcsArtifactService`).
- `initialize_memory_service(component) -> BaseMemoryService`: Creates a memory service (e.g., `InMemoryMemoryService`).

#### setup.py
**Purpose:** The main entry point for configuring and instantiating the ADK agent and its dependencies. These functions tie all the other modules together.
**Import:** `from agent.adk.setup import load_adk_tools, initialize_adk_agent, initialize_adk_runner`

**Classes/Functions/Constants:**
- `async load_adk_tools(component) -> Tuple[...]`: Loads all configured tools, including Python functions, MCP tools, and built-ins, wrapping them with `ADKToolWrapper`.
- `initialize_adk_agent(component, loaded_explicit_tools, ...)`: Creates an `AppLlmAgent` instance, assigns all the necessary callbacks from `callbacks.py`, and attaches the tools.
- `initialize_adk_

================================================================================

## Section 2: agent/adk/models/models_llm.txt

**Source file:** `agent/adk/models/models_llm.txt`

Here is the developer guide for the `models` directory.

## Quick Summary
This directory contains concrete implementations of the `BaseLlm` interface, acting as wrappers or clients for various Large Language Model APIs. These classes translate the ADK's standard `LlmRequest` into the format required by the specific LLM backend and parse the backend's response back into a standard `LlmResponse`.

## Files Overview
- `lite_llm.py`: An LLM client that uses the `litellm` library to support a wide variety of models from different providers.

## Developer API Reference

### lite_llm.py
**Purpose:** Provides the `LiteLlm` class, a `BaseLlm` implementation that interfaces with hundreds of LLM models through the `litellm` library. This allows developers to use models from providers like OpenAI, Anthropic, Vertex AI, etc., by simply changing the model string. Environment variables required by the target model provider must be set.

**Import:** `from google.adk.models.lite_llm import LiteLlm`

**Classes:**
- `LiteLlm(model: str, **kwargs)` - Wrapper around `litellm` that can be used with any model it supports.
  - `__init__(self, model: str, **kwargs)` - Initializes the `LiteLlm` client.
    - **model**: The name of the model as recognized by `litellm` (e.g., `"vertex_ai/gemini-1.5-pro-preview-0409"`, `"claude-3-opus-20240229"`, `"gpt-4-turbo"`).
    - **\*\*kwargs**: Additional arguments to pass directly to the `litellm.completion` or `litellm.acompletion` API on every call.
  - `async generate_content_async(llm_request: LlmRequest, stream: bool = False) -> AsyncGenerator[LlmResponse, None]` - Sends a request to the configured LLM and yields one or more responses.
    - **llm_request**: The request object containing conversation history, tool definitions, and configuration.
    - **stream**: If `True`, yields partial responses as they become available. If `False`, yields a single, complete response.
    - **Returns**: An async generator that yields `LlmResponse` objects.
  - `supported_models() -> list[str]` - Provides a list of supported models. For `LiteLlm`, this returns an empty list because `litellm` supports a vast and dynamic set of models. Refer to the `litellm` documentation for a complete list.

**Usage Examples:**
```python
import asyncio
import os
from google.adk.models.lite_llm import LiteLlm
from google.adk.models.llm_request import LlmRequest, LlmConfig
from google.adk.models.types import Content, Part

# Example using a Vertex AI model via litellm.
# Set environment variables required by the provider.
# os.environ["VERTEXAI_PROJECT"] = "your-gcp-project-id"
# os.environ["VERTEXAI_LOCATION"] = "your-gcp-location"

# Example using an OpenAI model via litellm.
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key"

async def main():
    # Instantiate the LiteLlm client with a specific model.
    # Any additional kwargs are passed to litellm's completion call.
    llm = LiteLlm(
        model="gpt-4-turbo",
        temperature=0.5,
        max_tokens=150
    )

    # Construct a request to the LLM
    request = LlmRequest(
        contents=[
            Content(
                role="user",
                parts=[Part.from_text("Why is the sky blue?")]
            )
        ],
        config=LlmConfig(
            # The temperature set in the constructor can be overridden here
            temperature=0.7
        )
    )

    print("--- Non-streaming example ---")
    # Get a single, complete response
    async for response in llm.generate_content_async(request, stream=False):
        if response.text:
            print(response.text)
        if response.usage_metadata:
            print(f"Token usage: {response.usage_metadata.total_token_count}")

    print("\n--- Streaming example ---")
    # Get a stream of partial responses
    full_response_text = ""
    async for response in llm.generate_content_async(request, stream=True):
        if response.text:
            print(response.text, end="", flush=True)
            full_response_text += response.text
        if response.usage_metadata:
            # Usage metadata is typically sent with the final chunk
            print(f"\nToken usage: {response.usage_metadata.total_token_count}")

if __name__ == "__main__":
    # To run this example, you need to have the necessary environment variables set
    # for the model you choose (e.g., OPENAI_API_KEY).
    # You would also need to install the required provider packages, e.g.,
    # pip install litellm[openai]
    #
    # Since this is an async function, we run it with asyncio.
    # asyncio.run(main())
    pass
```

================================================================================

## Section 3: agent/agent_llm.txt

**Source file:** `agent/agent_llm.txt`

Here is the comprehensive developer guide for the `agent` directory.

## Quick Summary
The `agent` directory provides a comprehensive framework for hosting Google ADK (Agent Development Kit) agents within the Solace AI Connector ecosystem. It bridges ADK agents with the A2A (Agent-to-Agent) protocol over Solace messaging, enabling distributed agent communication, task delegation, and rich tool functionality.

The architecture is modular, consisting of several key components:
*   **`sac/` (Solace AI Connector):** The main entry point, providing the `SamAgentApp` and `SamAgentComponent` to host the agent and manage its lifecycle and communication over the Solace event mesh.
*   **`adk/` (Agent Development Kit):** The core integration layer with Google's ADK. It defines the custom `AppLlmAgent`, manages asynchronous task execution, and provides a rich set of callbacks to augment agent behavior.
*   **`tools/`:** A comprehensive and extensible library of tools available to the agent, covering data analysis, artifact management, web requests, multimedia processing, and inter-agent communication.
*   **`protocol/`:** The underlying implementation of the A2A (Agent-to-Agent) communication protocol, handling message routing and event processing.
*   **`utils/`:** A collection of helper modules for common tasks like artifact management, configuration parsing, and context handling.
*   **`testing/`:** Utilities to aid in debugging and testing custom agent implementations.

These components work together to create a robust environment where an ADK agent can be configured with specific instructions and tools, communicate with other agents, and execute complex tasks in a distributed, event-driven manner.

## Files and Subdirectories Overview
- **Direct files:**
  - `__init__.py`: An empty file that marks the `agent` directory as a Python package.
- **Subdirectories:**
  - `adk/`: Provides the core integration layer with Google's ADK, including custom agents, services, and callbacks.
  - `protocol/`: Implements the A2A protocol event handlers for message routing and agent communication.
  - `sac/`: Contains the Solace AI Connector app and component implementations for hosting ADK agents.
  - `testing/`: Provides utilities for testing the A2A framework and debugging agent behavior.
  - `tools/`: A comprehensive, registry-based tool library for AI agents.
  - `utils/`: Contains helper utilities for configuration, context handling, and artifact management.

## Developer API Reference

### Direct Files

#### __init__.py
**Purpose:** Standard Python package initializer. It allows the `agent` directory to be treated as a package.
**Import:** `import agent`

**Classes/Functions/Constants:** [None]

### Subdirectory APIs

#### adk/
**Purpose:** Provides the core integration layer between the Solace AI Connector and Google's ADK.
**Key Exports:** `App

================================================================================

## Section 4: agent/protocol/protocol_llm.txt

**Source file:** `agent/protocol/protocol_llm.txt`

## Quick Summary
The `protocol` directory implements the core logic for Agent-to-Agent (A2A) communication. It handles receiving and processing requests, responses, and discovery messages (Agent Cards) over the Solace event mesh. It acts as the bridge between the A2A protocol and the underlying Google ADK execution environment.

## Files Overview
- `__init__.py` - An empty file that marks the directory as a Python package.
- `event_handlers.py` - Contains the primary logic for handling all A2A protocol events, including routing incoming messages to the correct processors, managing task execution, and handling agent discovery.

## Developer API Reference

### __init__.py
**Purpose:** Standard Python package initialization file.
**Import:** `from src.solace_agent_mesh.agent.protocol import *`

This is an empty package initialization file and has no public interfaces.

### event_handlers.py
**Purpose:** This file is the central hub for processing all events related to the A2A protocol. It receives events from the Solace AI Connector framework, determines their type (e.g., new task request, peer agent response, discovery message, timer), and routes them to the appropriate handler function. It manages the lifecycle of tasks, from initiation and cancellation to handling responses from peer agents.
**Import:** `from src.solace_agent_mesh.agent.protocol.event_handlers import process_event, handle_a2a_request, handle_agent_card_message, handle_a2a_response, publish_agent_card`

**Functions:**
- `process_event(component: "SamAgentComponent", event: Event

================================================================================

## Section 5: agent/sac/sac_llm.txt

**Source file:** `agent/sac/sac_llm.txt`

## Quick Summary
The `sac` (Solace AI Connector) directory provides the core implementation for hosting a Google ADK (Agent Development Kit) agent within the Solace AI Connector framework. It acts as a bridge, enabling ADK agents to communicate using the A2A (Agent-to-Agent) protocol over Solace messaging. This allows for the creation of distributed, collaborative agent systems where agents can delegate tasks, share information, and work together to solve complex problems.

The main components are `SamAgentApp`, which handles the initial setup and configuration, and `SamAgentComponent`, which hosts the ADK agent instance, manages its lifecycle, and translates between the A2A protocol and the ADK's internal event model.

## Files Overview
- `__init__.py`: An empty file that marks the `sac` directory as a Python package.
- `app.py`: Defines a custom SAC `App` class that automatically configures Solace subscriptions and broker settings for A2A communication.
- `component.py`: The main SAC `Component` that hosts the ADK agent, manages its lifecycle, and handles all A2A protocol messaging.
- `patch_adk.py`: Contains runtime patches for the Google ADK library to enhance or correct its behavior for this specific use case.
- `task_execution_context.py`: A state management class that encapsulates all runtime information for a single, in-flight A2A task.

## Developer API Reference

---
### __init__.py
**Purpose:** A standard Python file that makes the `sac` directory a package, allowing its modules to be imported.
**Import:** This file is not meant to be imported from directly.

---
### app.py
**Purpose:** Provides a custom SAC `App` class (`SamAgentApp`) that simplifies the configuration of an A2A agent. It automatically generates the required Solace topic subscriptions and configures the message broker based on the provided `namespace` and `agent_name` in the configuration file. This class is the main entry point for running an agent host.
**Import:** `from src.solace_agent_mesh.agent.sac.app import SamAgentApp`

**Classes:**
- `SamAgentApp(app_info: Dict[str, Any], **kwargs)` - A custom App class for the SAM Agent Host. It handles namespace prefixing, automatic subscription generation, and programmatic definition of the `SamAgentComponent`.
  - `app_schema: Dict` - A class attribute that defines the comprehensive configuration schema for the agent host. This schema is used by the SAC framework to validate the application's YAML configuration file, ensuring all required parameters are present and correctly typed.

**Constants/Variables:**
- `info: Dict[str, str]` - A dictionary containing metadata about the `SamAgentApp` class, required by the SAC framework for discovery.

**Usage Examples:**
```python
# The SamAgentApp is typically instantiated by the Solace AI Connector framework,
# not directly by a developer. The framework reads a YAML configuration file,
# validates it against the app_schema, and passes the resulting configuration
# to the SamAgentApp constructor.

# --- Example agent-config.yaml ---
# app:
#   class_name: src.solace_agent_mesh.agent.sac.app.SamAgentApp
#   app_config:
#     namespace: "my-org/production"
#     agent_name: "customer-support-agent"
#     model: "gemini-1.5-pro-latest"
#     tools:
#       - tool_type: "builtin"
#         tool_name: "file_search"
#     agent_card:
#       description: "An agent that can answer questions about customer accounts."
#     agent_card_publishing:
#       interval_seconds: 60
#     agent_discovery:
#       enabled: true
#     inter_agent_communication:
#       allow_list: ["*"]
#       request_timeout_seconds: 45
#     session_service:
#       type: "memory"
#     # ... other configuration parameters
```

---
### component.py
**Purpose:** This is the core component that hosts a Google ADK agent and bridges its communication to the A2A protocol over Solace. It handles incoming task requests, manages the agent's lifecycle, processes ADK events, orchestrates tool calls (including peer agent delegation), and sends status updates and final responses. Developers can interact with this component's state and lifecycle via custom initialization and cleanup functions.
**Import:** `from src.solace_agent_mesh.agent.sac.component import SamAgentComponent`

**Classes:**
- `SamAgentComponent(**kwargs)` - A Solace AI Connector component that hosts a Google ADK agent and communicates via the A2A protocol.
  - `process_event(self, event: Event)` - The main entry point for all events from the SAC framework (e.g., incoming messages, timers). This method orchestrates the processing of A2A requests.
  - `handle_timer_event(self, timer_data: Dict[str, Any])` - Handles scheduled timer events, primarily used for periodically publishing the agent's discovery card.
  - `handle_cache_expiry_event(self, cache_data: Dict[str, Any])` - Handles cache expiry events, used to detect timeouts for requests sent to peer agents.
  - `finalize_task_success(self, a2a_context: Dict)` - An async method that finalizes a task successfully, sending the final `COMPLETED` response.
  - `finalize_task_canceled(self, a2a_context: Dict)` - Finalizes a task as `CANCELED` and sends the corresponding response.
  - `finalize_task_error(self, exception: Exception, a2a_context: Dict)` - An async method that finalizes a task as `FAILED`, sending an error response.
  - `cleanup(self)` - Cleans up all resources when the component is shut down, including stopping the async loop and calling any custom cleanup functions.
  - `set_agent_specific_state(self, key: str, value: Any)` - Sets a key-value pair in a dedicated state dictionary. This is intended for use within a custom `agent_init_function` to store state (e.g., database connections, API clients) that can be accessed by tools.
  - `get_agent_specific_state(self, key: str, default: Optional[Any] = None) -> Any` - Retrieves a value from the agent-specific state dictionary. This is intended for use by tools or a custom `agent_cleanup_function`.
  - `get_async_loop(self) -> Optional[asyncio.AbstractEventLoop]` - Returns the dedicated asyncio event loop used by the component for all its asynchronous operations. This is useful for scheduling custom async work from synchronous code (e.g., tools).
  - `set_agent_system_instruction_string(self, instruction_string: str) -> None` - Sets a static string to be injected into the agent's system prompt. This should be called from a custom `agent_init_function`.
  - `set_agent_system_instruction_callback(self, callback_function: Callable[[CallbackContext, LlmRequest], Optional[str]]) -> None` - Sets a callback function to dynamically generate parts of the system prompt at runtime. This should be called from a custom `agent_init_function`.
  - `get_gateway_id(self) -> str` - Returns a unique identifier for this agent host instance, typically the agent's name.
  - `submit_a2a_task(self, target_agent_name: str, a2a_message: A2AMessage, original_session_id: str, main_logical_task_id: str, user_id: str, user_config: Dict[str, Any], sub_task_id: str, function_call_id: Optional[str] = None) -> str` - Submits a task to a peer agent in a non-blocking way. This is the core mechanism for agent delegation. Returns the `sub_task_id` used for correlation.
  - `get_agent_context(self) -> Dict[str, Any]` - Returns a dictionary containing context about the agent, used for interactions with the middleware system.

**Constants/Variables:**
- `info: Dict` - A dictionary containing metadata about the `SamAgentComponent` class, required by the SAC framework.
- `CORRELATION_DATA_PREFIX: str` - A public constant string used as a prefix for cache keys when tracking peer-to-peer requests.
- `HOST_COMPONENT_VERSION: str` - The version string of the host component.

**Usage Examples:**
```python
# This component is instantiated by the SamAgentApp. Developers interact with it
# primarily through custom init/cleanup functions and by building tools that
# may need access to its state or methods.

# --- In a custom init module (e.g., my_agent_init.py) ---
import asyncio
from src.solace_agent_mesh.agent.sac.component import SamAgentComponent
from src.solace_agent_mesh.common.types import A2AMessage, TextPart

# This function would be configured in the agent's YAML config
def initialize_my_agent(host_component: SamAgentComponent, config: dict):
    """Custom initialization function for the agent."""
    print("Initializing my custom agent...")

================================================================================

## Section 6: agent/testing/testing_llm.txt

**Source file:** `agent/testing/testing_llm.txt`

## Quick Summary

The `testing` directory provides a suite of utilities designed to facilitate the testing of the A2A (Agent-to-Agent) framework. Its primary function is to offer tools that simplify debugging and validation of agent interactions during test runs, particularly for declarative tests.

## Files Overview

-   `__init__.py`: Marks the directory as a Python package.
-   `debug_utils.py`: Provides helper functions for debugging test failures, most notably a pretty-printer for A2A event histories.

## Developer API Reference

### debug_utils.py

**Purpose:** This module contains utilities to help developers debug failing tests by providing human-readable representations of complex data structures, such as the event history from an A2A task.

**Import:** `from agent.testing.debug_utils import pretty_print_event_history`

**Functions:**

-   `pretty_print_event_history(event_history: List[Dict[str, Any]], max_string_length: int = 200) -> None`
    Formats and prints a list of A2A event payloads to the console in a structured, readable format. It intelligently parses different event types (status updates, final responses, errors) and truncates long strings to keep the output concise. This is invaluable for quickly diagnosing why a test failed by inspecting the sequence of events leading up to the failure.

**Usage Examples:**

```python
# Show how to import and use the main classes/functions
from agent.testing.debug_utils import pretty_print_event_history
from typing import List, Dict, Any

# Example event history captured during a test run
sample_event_history: List[Dict[str, Any]] = [
    {
        "result": {
            "status": {
                "state": "EXECUTING",
                "message": {
                    "parts": [
                        {"type": "text", "text": "Okay, I am starting the process to find the latest sales report."}
                    ]
                },
            },
            "final": False,
        }
    },
    {
        "result": {
            "artifact": {
                "name": "sales_report_q4.pdf",
                "parts": [
                    {
                        "type": "file",
                        "file": {
                            "name": "sales_report_q4.pdf",
                            "mimeType": "application/pdf",
                            "uri": "file://path/to/sales_report_q4.pdf"
                        }
                    }
                ]
            }
        }
    },
    {
        "error": {
            "code": "INTERNAL_ERROR",
            "message": "Failed to access the database due to a connection timeout. The database server at db.example.com might be down or unreachable. Please check the server status and network connectivity."
        }
    },
    {
        "result": {
            "status": {
                "state": "FAILED",
                "message": {
                    "parts": [
                        {"type": "text", "text": "I encountered an error and could not complete the task."}
                    ]
                }
            },
            "sessionId": "task-12345",
        }
    }
]

# In a test's `tearDown` or `except` block, you can print the history.
print("A test failed! Dumping the event history for review:")
pretty_print_event_history(sample_event_history, max_string_length=100)

# Example with no events
print("\n--- Example with no events ---")
pretty_print_event_history([])
```

================================================================================

## Section 7: agent/tools/tools_llm.txt

**Source file:** `agent/tools/tools_llm.txt`

## Quick Summary
The `tools` directory contains the complete set of built-in tools available to the agent. It follows a declarative, registry-based pattern where each tool module defines its functions and registers them with a central `tool_registry`. This allows for automatic discovery and dynamic availability of tools based on configuration and agent capabilities. The tools cover a wide range of functionalities including artifact management, audio/image processing, data analysis, web requests, and inter-agent communication.

## Files Overview
- `__init__.py`: Imports all tool modules, triggering their registration with the central registry.
- `audio_tools.py`: Provides tools for text-to-speech (TTS), multi-speaker TTS, audio concatenation, and transcription.
- `builtin_artifact_tools.py`: Contains core tools for creating, listing, loading, modifying, and deleting artifacts.
- `builtin_data_analysis_tools.py`: Offers tools for generating charts from Plotly configurations.
- `general_agent_tools.py`: Includes general-purpose utilities like file-to-markdown conversion and Mermaid diagram generation.
- `image_tools.py`: Provides tools for image generation, editing, and vision-based description of images and audio.
- `peer_agent_tool.py`: Defines the `PeerAgentTool` class for delegating tasks to other agents.
- `registry.py`: Implements the singleton `tool_registry` for managing all tool definitions.
- `test_tools.py`: Contains tools specifically for testing agent behavior, such as delays and failures.
- `tool_definition.py`: Defines the `BuiltinTool` Pydantic model used for declaring tools.
- `web_tools.py`: Contains a tool for making HTTP requests to external web resources.

## Developer API Reference

### __init__.py
**Purpose:** This file ensures that all built-in tool modules are imported when the `tools` package is loaded. This is crucial for the declarative tool registration pattern, as it triggers the `tool_registry.register()` calls within each tool module.
**Import:** `import src.solace_agent_mesh.agent.tools`

**Usage Examples:**
```python
# Importing the tools package is sufficient to register all built-in tools.
import src.solace_agent_mesh.agent.tools

# You can then access the registry to see all registered tools.
from src.solace_agent_mesh.agent.tools.registry import tool_registry
all_tools = tool_registry.get_all_tools()
print(f"Registered {len(all_tools)} tools.")
```

### audio_tools.py
**Purpose:** This file provides a collection of tools for audio processing, including text-to-speech (TTS) generation, audio concatenation, and transcription.
**Import:** `from src.solace_agent_mesh.agent.tools.audio_tools import select_voice, text_to_speech, multi_speaker_text_to_speech, concatenate_audio, transcribe_audio`

**Functions:**
- `select_voice(gender: Optional[str] = None, tone: Optional[str] = None, exclude_voices: Optional[List[str]] = None, tool_context: ToolContext = None, tool_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]` - Selects a suitable voice name based on criteria like gender and tone. Use this to get a consistent voice name that can be passed to the `text_to_speech` tool for multiple calls.
- `text_to_speech(text: str, output_filename: Optional[str] = None, voice_name: Optional[str] = None, gender: Optional[str] = None, tone: Optional[str] = None, language: Optional[str] = None, tool_context: ToolContext = None, tool_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]` - Converts text to speech using Gemini TTS API and saves as an MP3 artifact.
- `multi_speaker_text_to_speech(conversation_text: str, output_filename: Optional[str] = None, speaker_configs: Optional[List[Dict[str, str]]] = None, language: Optional[str] = None, tool_context: ToolContext = None, tool_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]` - Converts conversation text with speaker labels to speech using multiple voices.
- `concatenate_audio(clips_to_join: List[Dict[str, Any]], output_filename: Optional[str] = None, tool_context: ToolContext = None, tool_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]` - Combines multiple audio artifacts in a specified order into a single audio file, with optional pauses.
- `transcribe_audio(audio_filename: str, tool_context: ToolContext = None, tool_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]` - Transcribes an audio recording using an OpenAI-compatible audio transcription API.

**Constants/Variables:**
- `ALL_AVAILABLE_VOICES: List[str]` - A list of all available voice names for TTS.
- `SUPPORTED_LANGUAGES: Dict[str, str]` - A mapping of common language names to their BCP-47 codes.
- `VOICE_TONE_MAPPING: Dict[str, List[str]]` - A dictionary mapping descriptive tones to lists of voice names.
- `GENDER_TO_VOICE_MAPPING: Dict[str, List[str]]` - A dictionary mapping genders ('male', 'female', 'neutral') to lists of voice names.

**Usage Examples:**
```python
# Assume 'tool_context' is a valid ToolContext object.

# 1. Generate a simple audio file
tts_result = await text_to_speech(
    text="Welcome to the developer guide.",
    output_filename="welcome.mp3",
    gender="female",
    tone="friendly",
    language="en-US",
    tool_context=tool_context
)
print(tts_result)

# 2. Generate a multi-speaker conversation
convo_result = await multi_speaker_text_to_speech(
    conversation_text="SpeakerA: How are you?\nSpeakerB: I am fine, thank you.",
    speaker_configs=[
        {"name": "SpeakerA", "gender": "male", "tone": "warm"},
        {"name": "SpeakerB", "gender": "female", "tone": "bright"}
    ],
    output_filename="dialogue.mp3",
    tool_context=tool_context
)
print(convo_result)

# 3. Concatenate the generated audio files
concat_result = await concatenate_audio(
    clips_to_join=[
        {"filename": "welcome.mp3:1", "pause_after_ms": 500},
        {"filename": "dialogue.mp3:1"}
    ],
    output_filename="combined_audio.mp3",
    tool_context=tool_context
)
print(concat_result)

# 4. Transcribe the combined audio
transcribe_result = await transcribe_audio(
    audio_filename="combined_audio.mp3:1",
    tool_context=tool_context
)
print(transcribe_result)
```

### builtin_artifact_tools.py
**Purpose:** This file provides the core tools for artifact management, allowing the agent to create, read, list, update, and delete data artifacts within the current session.
**Import:** `from src.solace_agent_mesh.agent.tools.builtin_artifact_tools import list_artifacts, load_artifact, signal_artifact_for_return, append_to_artifact, apply_embed_and_create_artifact, extract_content_from_artifact, delete_artifact`

**Functions:**
- `list_artifacts(tool_context: ToolContext = None) -> Dict[str, Any]` - Lists all available data artifact filenames and their versions for the current session.
- `load_artifact(filename: str, version: int, load_metadata_only: bool = False, max_content_length: Optional[int] = None, tool_context: ToolContext = None) -> Dict[str, Any]` - Loads the content or metadata of a specific artifact version.
- `signal_artifact_for_return(filename: str, version: int, tool_context: ToolContext = None

================================================================================

## Section 8: agent/utils/utils_llm.txt

**Source file:** `agent/utils/utils_llm.txt`

## Quick Summary
The `utils` directory provides a collection of helper modules designed to support the core functionality of the agent. These utilities encapsulate common, reusable logic for tasks such as artifact management (saving, loading, schema inference), configuration parsing, and safe interaction with the ADK's invocation context.

## Files Overview
- `__init__.py` - An empty file that marks the directory as a Python package.
- `artifact_helpers.py` - Provides functions for creating, retrieving, and managing artifacts and their associated metadata.
- `config_parser.py` - Contains helpers for parsing and validating agent and app configurations.
- `context_helpers.py` - Offers utility functions for safely extracting data from ADK callback and invocation contexts.

## Developer API Reference

### artifact_helpers.py
**Purpose:** This module offers a comprehensive set of asynchronous functions for interacting with an artifact storage service. It handles saving artifacts with automatically generated metadata, inferring schemas for common data types, loading artifact content or just metadata, and listing available artifacts.
**Import:** `from src.solace_agent_mesh.agent.utils.artifact_helpers import is_filename_safe, ensure_correct_extension, save_artifact_with_metadata, load_artifact_content_or_metadata, get_latest_artifact_version, get_artifact_info_list, format_metadata_for_llm, decode_and_get_bytes`

**Functions:**
- `is_filename_safe(filename: str) -> bool` - Checks if a filename is safe for artifact creation (e.g., no path traversal).
- `ensure_correct_extension(filename_from_llm: str, desired_extension: str) -> str` - Corrects or adds the desired file extension to a filename.
- `save_artifact_with_metadata(artifact_service: BaseArtifactService, app_name: str, user_id: str, session_id: str, filename: str, content_bytes: bytes, mime_type: str, metadata_dict: Dict[str, Any], timestamp: datetime.datetime, explicit_schema: Optional[Dict] = None, schema_inference_depth: int = 2, schema_max_keys: int = 20, tool_context: Optional["ToolContext"] = None) -> Dict[str, Any]` - Asynchronously saves a data artifact and a corresponding metadata artifact, with optional schema inference.
- `format_metadata_for_llm(metadata: Dict[str, Any]) -> str` - Formats an artifact's metadata dictionary into a human-readable, LLM-friendly string.
- `decode_and_get_bytes(content_str: str, mime_type: str, log_identifier: str) -> Tuple[bytes, str]` - Decodes a string into bytes, handling base64 for binary MIME types and falling back to UTF-8 for text.
- `get_latest_artifact_version(artifact_service: BaseArtifactService, app_name: str, user_id: str, session_id: str, filename: str) -> Optional[int]` - Asynchronously retrieves the latest version number for a given artifact.
- `get_artifact_info_list(artifact_service: BaseArtifactService, app_name: str, user_id: str, session_id: str) -> List[ArtifactInfo]` - Asynchronously retrieves a list of detailed `ArtifactInfo` objects for all artifacts in the current context.
- `load_artifact_content_or_metadata(artifact_service: BaseArtifactService, app_name: str, user_id: str, session_id: str, filename: str, version: Union[int, str], load_metadata_only: bool = False, return_raw_bytes: bool = False, max_content_length: Optional[int] = None, component: Optional[Any] = None, encoding: str = "utf-8", error_handling: str = "strict") -> Dict[str, Any]` - Asynchronously loads an artifact's content or just its metadata for a specific version.

**Constants/Variables:**
- `METADATA_SUFFIX: str` - The suffix used for metadata files, `".metadata.json"`.
- `DEFAULT_SCHEMA_MAX_KEYS: int` - The default maximum number of keys to inspect when inferring a schema for a dictionary (default: 20).

**Usage Examples:**
```python
import asyncio
import datetime
from typing import Dict, Any, Optional, List, Union
from google.adk.artifacts import BaseArtifactService, MemoryArtifactService
from src.solace_agent_mesh.agent.utils.artifact_helpers import (
    save_artifact_with_metadata,
    load_artifact_content_or_metadata,
    get_artifact_info_list,
    ensure_correct_extension
)

# Assume 'service' is an instance of a BaseArtifactService implementation
service = MemoryArtifactService()
app_name = "my_app"
user_id = "user-1"
session_id = "session-1"

async def manage_artifacts():
    # 1. Ensure the filename from an LLM has the correct extension
    safe_filename = ensure_correct_extension("quarterly_report", "csv") # -> "quarterly_report.csv"

    # 2. Save an artifact with some metadata
    csv_content = b"id,name\n1,Alice\n2,Bob"
    save_result = await save_artifact_with_metadata(
        artifact_service=service,
        app_name=app_name,
        user_id=user_id,
        session_id=session_id,
        filename=safe_filename,
        content_bytes=csv_content,
        mime_type="text/csv",
        metadata_dict={"source": "manual_upload", "description": "User sales data"},
        timestamp=datetime.datetime.now(datetime.timezone.utc)
    )
    print(f"Save result: {save_result}")

    # 3. Load the content of the artifact we just saved
    loaded_artifact = await load_artifact_content_or_metadata(
        artifact_service=service,
        app_name=app_name,
        user_id=user_id,
        session_id=session_id,
        filename=safe_filename,
        version="latest"
    )
    if loaded_artifact.get("status") == "success":
        print(f"Loaded content: {loaded_artifact.get('content')}")

    # 4. List all available artifacts
    all_artifacts = await get_artifact_info_list(
        artifact_service=service,
        app_name=app_name,
        user_id=user_id,
        session_id=session_id
    )
    for artifact in all_artifacts:
        print(f"Found artifact: {artifact.filename} (v{artifact.version})")

# To run the async example
# asyncio.run(manage_artifacts())
```

### config_parser.py
**Purpose:** This module provides a utility to resolve configuration values that can be either a static string or a dynamic, callable "invoke" block. This is primarily used for parsing the agent's `instruction` configuration.
**Import:** `from src.solace_agent_mesh.agent.utils.config_parser import resolve_instruction_provider`

**Functions:**
- `resolve_instruction_provider(component, config_value: Any) -> Union[str, Callable[[ReadonlyContext], str]]` - Resolves an instruction from a configuration value. If the value is a string, it's returned directly. If it's a dictionary with an "invoke" key that resolves to a callable, the callable is returned.

**Usage Examples:**
```python
# Assume 'my_agent_component' is an instance of an agent component
# and it has a method 'get_config'

# Example 1: Config value is a simple string
config_str = "You are a helpful assistant."
instruction = resolve_instruction_provider(my_agent_component, config_str)
# instruction is "You are a helpful assistant."

# Example 2: Config value is a callable (e.g., from a YAML 'invoke' block)
def instruction_provider(context):
    return f"Assistant for user {context.user_id}"

instruction_func = resolve_instruction_provider(my_agent_component, instruction_provider)
# instruction_func is the instruction_provider function
```

### context_helpers.py
**Purpose:** This module provides safe and stable helper functions to extract information from the ADK's `CallbackContext` and other invocation context objects, abstracting away internal attribute access.
**Import:** `from src.solace_agent_mesh.agent.utils.context_helpers import get_session_from_callback_context, get_original_session_id`

**Functions:**
- `get_session_from_callback_context(callback_context: CallbackContext) -> Session` - Safely retrieves the persistent `Session` object from a `CallbackContext`.
- `get_original_session_id(invocation_context: Any) -> str` - Extracts the base session ID from a context, stripping any suffixes added after a colon (e.g., "session123:tool456" -> "session123").

**Usage Examples:**
```python
from google.adk.agents.callback_context import CallbackContext
from google.adk.sessions import Session, SessionId
from src.solace_agent_mesh.agent.utils.context_helpers import get_session_from_callback_context, get_original_session_id

# Mock context objects for demonstration
class MockInvocationContext:
    def __init__(self, session_id_str: str):
        self.session = Session(id=SessionId(session_id_str))

# 1. Get the full session object from a callback context
# In a real tool, 'callback_context' is provided by the ADK
mock_callback_context = CallbackContext(_invocation_context=MockInvocationContext("session123:tool456"))
session_obj = get_session_from_callback_context(mock_callback_context)
print(f"Full Session ID: {session_obj.id}") # -> "session123:tool456"

# 2. Get the original session ID from an invocation context
# In a real tool, this comes from 'tool_context._invocation_context'
mock_inv_context = MockInvocationContext("session123:tool456")
original_id = get_original_session_id(mock_inv_context)
print(f"Original Session ID: {original_id}") # -> "session123"

# Works with simple IDs too
mock_inv_context_simple = MockInvocationContext("session789")
original_id_simple = get_original_session_id(mock_inv_context_simple)
print(f"Original Session ID (simple): {original_id_simple}") # -> "session789

================================================================================

## Section 9: common/client/client_llm.txt

**Source file:** `common/client/client_llm.txt`

## Quick Summary
The `client` directory provides a Python-based client library for Agent-to-Agent (A2A) communication. It allows developers to discover remote agent capabilities via an "Agent Card" and then interact with that agent by sending tasks, receiving streaming responses, and managing the task lifecycle (getting status, cancelling, setting callbacks).

## Files Overview
- `__init__.py`: Exposes the primary `A2AClient` and `A2ACardResolver` classes for easy importing.
- `card_resolver.py`: Contains the `A2ACardResolver` class, used to discover and fetch an agent's capabilities from a well-known endpoint.
- `client.py`: Contains the main `A2AClient` class for all communication with a remote agent, including sending tasks and managing them.

## Developer API Reference

### __init__.py
**Purpose:** This file makes the main client classes available directly under the `client` package, simplifying imports for developers.
**Import:** `from src.solace_agent_mesh.common.client import A2AClient, A2ACardResolver`

**Constants/Variables:**
- `__all__: list[str]` - A list of the public objects that are exported from this module: `["A2AClient", "A2ACardResolver"]`.

---

### card_resolver.py
**Purpose:** This file provides a utility to resolve and fetch an agent's "Agent Card". The Agent Card is a JSON file that describes the agent's capabilities, its endpoint URL, and other metadata.
**Import:** `from src.solace_agent_mesh.common.client import A2ACardResolver`

**Classes:**
- `A2ACardResolver(base_url: str, agent_card_path: str = "/.well-known/agent.json")` - A client to discover and fetch an agent's capability card.
  - `get_agent_card() -> AgentCard` - Makes an HTTP GET request to the constructed agent card URL, parses the JSON response, and returns it as an `AgentCard` object. Raises `A2AClientHTTPError` on network/status errors and `A2AClientJSONError` on parsing errors.

**Usage Examples:**
```python
from src.solace_agent_mesh.common.client import A2ACardResolver
from src.solace_agent_mesh.common.types import AgentCard, A2AClientHTTPError

# --- Example 1: Standard usage ---
# Create a resolver for an agent hosted at a specific domain
resolver = A2ACardResolver(base_url="https://some-agent.ai")

try:
    # Fetch the agent's capability card from the default path
    # (https://some-agent.ai/.well-known/agent.json)
    agent_card: AgentCard = resolver.get_agent_card()
    print(f"Successfully fetched card for agent: {agent_card.name}")
    print(f"Agent API URL: {agent_card.url}")
    print(f"Supported capabilities: {agent_card.capabilities}")

except A2AClientHTTPError as e:
    print(f"Error fetching agent card: {e.status_code} - {e.message}")


# --- Example 2: Using a custom path for the agent card ---
custom_path_resolver = A2ACardResolver(
    base_url="https://another-agent.com",
    agent_card_path="/api/v1/agent-info.json"
)
# This will fetch from https://another-agent.com/api/v1/agent-info.json
custom_agent_card = custom_path_resolver.get_agent_card()
print(f"Agent name from custom path: {custom_agent_card.name}")
```

---

### client.py
**Purpose:** This file contains the core `A2AClient`, which is used to communicate with a remote agent's API endpoint. It handles sending various types of JSON-RPC requests for task management. All methods are asynchronous.
**Import:** `from src.solace_agent_mesh.common.client import A2AClient`

**Classes:**
- `A2AClient(agent_card: AgentCard = None, url: str = None)` - The main client for interacting with a remote agent. You must provide either an `AgentCard` object (from `A2ACardResolver`) or a direct `url` string to its API endpoint.
  - `async send_task(self, payload: dict[str, Any]) -> SendTaskResponse` - Sends a task to the agent for processing. The `payload` should contain the action and its parameters. Returns a response typically containing a `task_id`.
  - `async send_task_streaming(self, payload: dict[str, Any]) -> AsyncIterable[SendTaskStreamingResponse]` - Sends a task that is expected to return a stream of events (Server-Sent Events). The `payload` is the same as `send_task`. Returns an async iterator that yields response chunks as they arrive.
  - `async get_task(self, payload: dict[str, Any]) -> GetTaskResponse` - Retrieves the current status and/or result of a previously submitted task. The `payload` must contain the `task_id`.
  - `async cancel_task(self, payload: dict[str, Any]) -> CancelTaskResponse` - Requests the cancellation of a running task. The `payload` must contain the `task_id`.
  - `async set_task_callback(self, payload: dict[str, Any]) -> SetTaskPushNotificationResponse` - Sets a callback URL for a specific task. The agent will send a notification to this URL upon task completion. The `payload` must contain the `task_id` and `callback_url`.
  - `async get_task_callback(self, payload: dict[str, Any]) -> GetTaskPushNotificationResponse` - Retrieves the currently configured callback URL for a task. The `payload` must contain the `task_id`.

**Usage Examples:**
```python
import asyncio
from src.solace_agent_mesh.common.client import A2AClient, A2ACardResolver

# Assume these types are available for type hinting
# from src.solace_agent_mesh.common.types import SendTaskResponse, SendTaskStreamingResponse

async def main():
    # First, discover the agent's capabilities and endpoint URL
    resolver = A2ACardResolver(base_url="https://some-agent.ai")
    agent_card = resolver.get_agent_card()

    # --- Initialization ---
    # Method 1: Initialize client using the discovered AgentCard
    client = A2AClient(agent_card=agent_card)

    # Method 2: Initialize client with a direct URL (if known)
    # client = A2AClient(url="https://some-agent.ai/api/v1/a2a")

    # --- Send a simple task ---
    print("--- Sending a simple task ---")
    task_payload = {"action": "summarize_text", "text": "A long article..."}
    send_response = await client.send_task(payload=task_payload)
    task_id = send_response.result.task_id
    print(f"Task created with ID: {task_id}")

    # --- Get task status ---
    print("\n--- Checking task status ---")
    status_response = await client.get_task(payload={"task_id": task_id})
    print(f"Task status: {status_response.result.status}")
    
    # --- Send a streaming task ---
    print("\n--- Sending a streaming task ---")
    stream_payload = {"action": "generate_story", "prompt": "A robot who discovers music"}
    async for chunk in client.send_task_streaming(payload=stream_payload):
        # Each chunk is a SendTaskStreamingResponse object
        print(f"Received stream chunk: {chunk.result.content_chunk}")

    # --- Set a callback URL for the task ---
    print("\n--- Setting a callback URL ---")
    await client.set_task_callback(
        payload={"task_id": task_id, "callback_url": "https://my-app.com/webhook"}
    )
    print("Callback URL set.")

    # --- Cancel a task ---
    print("\n--- Cancelling a task ---")
    cancel_response = await client.cancel_task(payload={"task_id": task_id})
    print(f"Task cancellation requested. Success: {cancel_response.result.cancelled}")


if __name__ == "__main__":
    # Note: In a real application, you would use a running event loop.
    # This example assumes the agent endpoint is available and working.
    # To run this, you would need a live agent to connect to.
    # asyncio.run(main())
    print("Developer guide example executed.")

```

================================================================================

## Section 10: common/common_llm.txt

**Source file:** `common/common_llm.txt`

Here is the comprehensive developer guide for the `common` directory.

## Quick Summary
The `common` directory provides the foundational infrastructure for Agent-to-Agent (A2A) communication within the Solace AI Connector. It establishes the core protocol, data types, and message translation logic that underpins all interactions between AI agents and gateways.

The architecture is designed for clarity and extensibility. Core, low-level definitions are located in **direct files**:
*   `types.py` defines the canonical data structures (e.g., `Message`, `Task`, `AgentCard`).
*   `a2a_protocol.py` handles the construction of Solace topics and the translation between A2A and Google ADK message formats.
*   `agent_registry.py` provides a simple, thread-safe mechanism for discovering and tracking available agents.

This foundation is then leveraged by specialized **subdirectories**, which provide higher-level, ready-to-use components:
*   `client/`: A complete client library for discovering and interacting with remote agents.
*   `server/`: A stand-alone server implementation for building A2A-compliant agents.
*   `middleware/`: A pluggable framework for customizing configuration and feature access.
*   `services/`: A factory-based system for integrating identity and other external data sources.
*   `utils/`: A collection of cross-cutting utilities for caching, logging, and dynamic content processing.

Together, these components form a cohesive ecosystem, enabling developers to either build new agents from scratch using the `server` components or interact with existing agents using the `client` library, all while relying on the same underlying protocol and types.

## Files and Subdirectories Overview
- **Direct files:**
    - `__init__.py`: Package initialization file.
    - `a2a_protocol.py`: Handles A2A topic construction and translation between A2A and ADK message formats.
    - `agent_registry.py`: A thread-safe registry for managing discovered agent cards.
    - `types.py`: Contains all Pydantic models for A2A protocol messages, tasks, and data structures.
- **Subdirectories:**
    - `client/`: Provides a high-level client for discovering and communicating with remote A2A agents.
    - `middleware/`: A pluggable framework for configuration resolution and system extensibility.
    - `server/`: A complete A2A server implementation with JSON-RPC support and task management.
    - `services/`: Provides shared services like identity management using a factory pattern.
    - `utils/`: Contains common utility functions and an embedded expression processing system.

## Developer API Reference

### Direct Files

#### a2a_protocol.py
**Purpose:** Provides the core functions for constructing Solace topics according to the A2A specification and for translating messages between the A2A format and the Google ADK format.
**Import:** `from common.a2a_protocol import get_agent_request_topic, translate_a2a_to_adk_content`

**Classes/Functions/Constants:**
*   **Constants**:
    *   `A2A_VERSION: str`: The current version of the A2A protocol (e.g., "v1").
    *   `A2A_BASE_PATH: str`: The base path used in all A2A topics (e.g., "a2a/v1").
*   **Topic Construction Functions**:
    *   `get_a2a_base_topic(namespace: str) -> str`: Returns the base topic prefix for all A2A communication.
    *   `get_discovery_topic(namespace: str) -> str`: Returns the topic for agent card discovery.
    *   `get_agent_request_topic(namespace: str, agent_name: str) -> str`: Returns the topic for sending requests to a specific agent.
    *   `get_gateway_status_topic(namespace: str, gateway_id: str, task_id: str) -> str`: Returns the topic for an agent to publish status updates to a gateway.
    *   `get_gateway_response_topic(namespace: str, gateway_id: str, task_id: str) -> str`: Returns the topic for an agent to publish final responses to a gateway.
    *   `get_client_response_topic(namespace: str, client_id: str) -> str`: Returns the topic for publishing final responses to a specific client.
    *   `get_client_status_topic(namespace: str, client_id: str, task_id: str) -> str`: Returns the topic for publishing status updates to a specific client.
    *   ... and various functions for subscription topics (e.g., `get_gateway_status_subscription_topic`).
*   **Message Translation Functions**:
    *   `translate_a2a_to_adk_content(a2a_message: A2AMessage, log_identifier: str) -> adk_types.Content`: Translates an A2A `Message` object into the Google ADK `Content` format.
    *   `format_adk_event_as_a2a(...) -> Tuple[Optional[JSONRPCResponse], ...]`: Translates an ADK `Event` into an A2A `JSONRPCResponse` containing a `TaskStatusUpdateEvent`.
    *   `format_and_route_adk_event(...) -> Tuple[Optional[Dict], Optional[str], ...]`: A higher-level wrapper that formats an ADK event and determines the correct Solace topic to publish it to.

#### agent_registry.py
**Purpose:** Provides a simple, thread-safe, in-memory store for discovered `AgentCard` objects. This is useful for components that need to keep track of available agents in the network.
**Import:** `from common.agent_registry import AgentRegistry`

**Classes/Functions/Constants:**
*   **`AgentRegistry`**: A thread-safe class for storing and managing agent cards.
    *   `add_or_update_agent(self, agent_card: AgentCard)`: Adds a new agent or updates an existing one.
    *   `get_agent(self, agent_name: str) -> Optional[AgentCard]`: Retrieves an agent card by its unique name.
    *   `get_agent_names(self) -> List[str]`: Returns a sorted list of all discovered agent names.
    *   `clear(self)`: Clears all agents from the registry.

#### types.py
**Purpose:** Defines all the Pydantic data models that constitute the A2A protocol. These types ensure data consistency and provide validation across all components.
**Import:** `from common.types import Message, Task, AgentCard, JSONRPCRequest, TaskState`

**Classes/Functions/Constants:**
*   **Core Data Structures**:
    *   `Message`: Represents a message from a user or agent, containing a list of `Part` objects.
    *   `Part`: A discriminated union of `TextPart`, `FilePart`, and `DataPart`.
    *   `Task`: The central object representing a complete task, including its ID, status, history, and artifacts.
    *   `TaskStatus`: Describes the current state of a task (e.g., `WORKING`, `COMPLETED`).
    *   `TaskState(Enum)`: An enumeration of all possible task states.
    *   `AgentCard`: A comprehensive description of an agent's identity, capabilities, and skills.
    *   `Artifact`: Represents a task output, such as a generated file or structured data.
*   **JSON-RPC Structures**:
    *   `JSONRPCRequest`: The base model for all JSON-RPC requests.
    *   `JSONRPCResponse`: The base model for all JSON-RPC responses.
    *   `SendTaskRequest`, `GetTaskRequest`, etc.: Specific request types inheriting from `JSONRPCRequest`.
*   **Error Structures**:
    *   `JSONRPCError`: The base model for errors.
    *   `InternalError`, `TaskNotFoundError`, etc.: Specific error types inheriting from `JSONRPCError`.

### Subdirectory APIs

#### client/
**Purpose:** Provides a high-level, asynchronous client library for discovering and interacting with remote A2A agents.
**Key Exports:** `A2AClient`, `A2ACardResolver`
**Import Examples:**
```python
from common.client import A2AClient, A2ACardResolver
```

#### middleware/
**Purpose:** A pluggable middleware framework for customizing system behavior, such as resolving user-specific configurations and feature flags.
**Key Exports:** `ConfigResolver`, `MiddlewareRegistry`
**Import Examples:**
```python
from common.middleware import ConfigResolver, MiddlewareRegistry
```

#### server/
**Purpose:** A complete, stand-alone server for building A2A-compliant agents, handling HTTP requests, JSON-RPC, and task lifecycle management.
**Key Exports:** `A2AServer`, `TaskManager`, `InMemoryTaskManager`
**Import Examples:**
```python
from common.server import A2AServer, TaskManager, InMemoryTaskManager
```

#### services/
**Purpose:** A factory-based system for integrating external data sources for identity, employee information, and more.
**Key Exports:** `BaseIdentityService`, `create_identity_service`
**Import Examples:**
```python
from common.services.identity_service import create_identity_service, BaseIdentityService
```

#### utils/
**Purpose:** A collection of cross-cutting utilities for caching, logging, MIME type handling, and dynamic content processing.
**Key Exports:** `InMemoryCache`, `is_text_based_mime_type`, `resolve_embeds_in_string`
**Import Examples:**
```python
from common.utils.in_memory_cache import InMemoryCache
from common.utils import is_text_based_mime_type
from common.utils.embeds import resolve_embeds_in_string
```

## Complete Usage Guide
These examples demonstrate how to use the components from the `common` directory to build and interact with A2A agents.

### 1. How to import and use classes from direct files
This example shows basic usage of the protocol, types, and agent registry, which form the foundation of any A2A component.

```python
import uuid
from common.a2a_protocol import get_agent_request_topic, get_gateway_status_topic
from common.types import AgentCard,

================================================================================

## Section 11: common/middleware/middleware_llm.txt

**Source file:** `common/middleware/middleware_llm.txt`

Here is the DEVELOPER GUIDE for the `middleware` directory.

## Quick Summary
The `middleware` directory provides a pluggable framework for system components that can be extended or replaced at runtime. It offers a registry system to dynamically bind custom implementations for core functionalities like configuration resolution. The default implementations provide permissive behavior, making them suitable for development and testing environments where all features are enabled by default.

## Files Overview
- `__init__.py`: Exposes the main public classes of the middleware package for easy importing.
- `config_resolver.py`: Defines the default, permissive configuration resolution middleware.
- `registry.py`: Provides the `MiddlewareRegistry` for dynamically binding custom middleware implementations.

## Developer API Reference

### __init__.py
**Purpose:** This file serves as the entry point to the `middleware` package, exporting the primary public interfaces for developers to use.

**Usage Examples:**
```python
# Import the main classes directly from the middleware package
from solace_ai_connector.common.middleware import ConfigResolver, MiddlewareRegistry

# Now you can use ConfigResolver and MiddlewareRegistry
print(ConfigResolver)
print(MiddlewareRegistry)
```

---

### config_resolver.py
**Purpose:** This file provides a pluggable interface for resolving user-specific configuration and determining feature availability. The default `ConfigResolver` class is permissive, allowing all operations and enabling all features, which is ideal for development or simple deployments.

**Import:** `from solace_ai_connector.common.middleware import ConfigResolver`

**Classes:**
- `ConfigResolver()` - A class containing static methods to resolve user-specific configuration and determine feature availability. This default implementation is permissive.
  - `resolve_user_config(user_identity: Any, gateway_context: Dict[str, Any], base_config: Dict[str, Any]) -> Dict[str, Any]` - (async) Resolves user-specific configuration. The default implementation returns the `base_config` unchanged.
  - `is_feature_enabled(user_config: Dict[str, Any], feature_descriptor: Dict[str, Any], context: Dict[str, Any]) -> bool` - Checks if a feature is enabled for a user. The default implementation always returns `True`.
  - `validate_operation_config(user_config: Dict[str, Any], operation_spec: Dict[str, Any], validation_context: Dict[str, Any]) -> Dict[str, Any]` - Validates if an operation is allowed for a user. The default implementation always returns a dictionary with `{'valid': True}`.
  - `filter_available_options(user_config: Dict[str, Any], available_options: List[Dict[str, Any]], filter_context: Dict[str, Any]) -> List[Dict[str, Any]]` - Filters a list of options based on user permissions. The default implementation returns the original `available_options` list.

**Usage Examples:**
```python
import asyncio
from solace_ai_connector.common.middleware import ConfigResolver

async def main():
    # Example user identity and base configuration
    user_id = "test-user@example.com"
    base_conf = {"api_key": "default_key", "allowed_models": ["gpt-3.5-turbo"]}

    # 1. Resolve user configuration (default implementation returns base_conf)
    user_config = await ConfigResolver.resolve_user_config(
        user_identity=user_id,
        gateway_context={"gateway_id": "gw-1"},
        base_config=base_conf
    )
    print(f"Resolved User Config: {user_config}")

    # 2. Check if a feature is enabled (default is always True)
    feature_desc = {"feature_type": "ai_tool", "function_name": "code_interpreter"}
    is_enabled = ConfigResolver.is_feature_enabled(
        user_config=user_config,
        feature_descriptor=feature_desc,
        context={}
    )
    print(f"Is Feature Enabled: {is_enabled}")

    # 3. Validate an operation (default is always valid)
    op_spec = {"operation_type": "model_inference", "model": "gpt-4"}
    validation = ConfigResolver.validate_operation_config(
        user_config=user_config,
        operation_spec=op_spec,
        validation_context={}
    )
    print(f"Operation Validation: {validation}")

    # 4. Filter available options (default returns all options)
    all_models = [
        {"name": "gpt-3.5-turbo", "provider": "openai"},
        {"name": "gpt-4", "provider": "openai"},
    ]
    available_models = ConfigResolver.filter_available_options(
        user_config=user_config,
        available_options=all_models,
        filter_context={"type": "language_model"}
    )
    print(f"Filtered Options: {available_models}")

if __name__ == "__main__":
    asyncio.run(main())
```

---

### registry.py
**Purpose:** This file provides the `MiddlewareRegistry`, a static class that allows developers to dynamically bind, or "plug in," their own custom middleware implementations at runtime. This is the core of the pluggable system.

**Import:** `from solace_ai_connector.common.middleware import MiddlewareRegistry`

**Classes:**
- `MiddlewareRegistry()` - A registry for managing middleware implementations. All methods are class methods.
  - `bind_config_resolver(resolver_class: Type)` - Binds a custom class that implements the `ConfigResolver` interface. This new class will be used for all subsequent configuration resolution calls.
  - `get_config_resolver() -> Type` - Returns the currently bound `ConfigResolver` class. If no custom resolver has been bound, it returns the default `ConfigResolver`.
  - `register_initialization_callback(callback: callable)` - Registers a function to be executed when `initialize_middleware()` is called. Useful for setting up custom middleware components at application startup.
  - `initialize_middleware()` - Executes all registered initialization callbacks. This should be called once during application startup.
  - `reset_bindings()` - Resets all bindings back to their defaults. This is primarily useful for testing environments.
  - `get_registry_status() -> Dict[str, Any]` - Returns a dictionary containing the current status of the registry, such as which resolver is bound.

**Usage Examples:**
```python
import asyncio
from typing import Any, Dict, List
from solace_ai_connector.common.middleware import MiddlewareRegistry, ConfigResolver

# 1. Define a custom ConfigResolver implementation
class MyCustomConfigResolver:
    """A custom resolver that only allows 'admin' users to use 'gpt-4'."""
    @staticmethod
    async def resolve_user_config(user_identity: Any, **kwargs) -> Dict[str, Any]:
        if user_identity == "admin":
            return {"role": "admin", "allowed_models": ["gpt-4", "gpt-3.5-turbo"]}
        return {"role": "user", "allowed_models": ["gpt-3.5-turbo"]}

    @staticmethod
    def validate_operation_config(user_config: Dict, operation_spec: Dict, **kwargs) -> Dict:
        model = operation_spec.get("model")
        if model and model not in user_config.get("allowed_models", []):
            return {"valid": False, "reason": f"Model '{model}' not allowed for this user."}
        return {"valid": True}
    
    # Inherit other methods from the default for simplicity
    is_feature_enabled = ConfigResolver.is_feature_enabled
    filter_available_options = ConfigResolver.filter_available_options

# 2. Define an initialization callback
def setup_custom_logging():
    print("Custom middleware initialization logic is running!")

# 3. Bind the custom components
MiddlewareRegistry.bind_config_resolver(MyCustomConfigResolver)
MiddlewareRegistry.register_initialization_callback(setup_custom_logging)

# 4. Initialize the middleware (e.g., at application startup)
print("--- Initializing Middleware ---")
MiddlewareRegistry.initialize_middleware()
print("--- Initialization Complete ---")

# 5. Use the middleware system
async def check_permissions():
    # The registry will now use MyCustomConfigResolver automatically
    CurrentResolver = MiddlewareRegistry.get_config_resolver()
    print(f"Current resolver is: {CurrentResolver.__name__}")

    # Check an admin user
    admin_config = await CurrentResolver.resolve_user_config("admin")
    validation_result = CurrentResolver.validate_operation_config(
        admin_config, {"model": "gpt-4"}
    )
    print(f"Admin validation for gpt-4: {validation_result}")

    # Check a regular user
    user_config = await CurrentResolver.resolve_user_config("user")
    validation_result = CurrentResolver.validate_operation_config(
        user_config, {"model": "gpt-4"}
    )
    print(f"User validation for gpt-4: {validation_result}")

# Run the example
asyncio.run(check_permissions())

# 6. Check status and reset (useful for testing)
print(f"\nRegistry Status: {MiddlewareRegistry.get_registry_status()}")
MiddlewareRegistry.reset_bindings()
print(f"Registry Status after reset: {MiddlewareRegistry.get_registry_status()}")
```

================================================================================

## Section 12: common/server/server_llm.txt

**Source file:** `common/server/server_llm.txt`

## Quick Summary
The `server` directory provides a complete, stand-alone Agent-to-Agent (A2A) communication server. It is built using Starlette and implements the JSON-RPC 2.0 protocol for handling various task-related requests, including standard request-response, task streaming via Server-Sent Events (SSE), and push notification management. It features an extensible task management system with a default in-memory implementation.

## Files Overview
- `__init__.py`: Exposes the primary public classes (`A2AServer`, `TaskManager`, `InMemoryTaskManager`) for easy access.
- `server.py`: Contains the main `A2AServer` class, which sets up the Starlette web application, defines HTTP endpoints, and routes incoming A2A requests to the task manager.
- `task_manager.py`: Defines the `TaskManager` abstract base class, which outlines the contract for handling all task operations, and provides a concrete `InMemoryTaskManager` implementation.
- `utils.py`: A collection of utility functions for creating standardized error responses and checking modality compatibility.

## Developer API Reference

### __init__.py
**Purpose:** This file makes the core server components available for direct import from the `server` package, simplifying access for developers.
**Import:** `from solace_ai_connector.common.server import A2AServer, TaskManager, InMemoryTaskManager`

---

### server.py
**Purpose:** Implements the core HTTP server for Agent-to-Agent (A2A) communication. It handles JSON-RPC request parsing, routing to the appropriate task manager methods, and response generation, including support for Server-Sent Events (SSE).
**Import:** `from solace_ai_connector.common.server import A2AServer`

**Classes:**
- `A2AServer(host: str = "0.0.0.0", port: int = 5000, endpoint: str = "/", agent_card: AgentCard = None, task_manager: TaskManager = None)` - A Starlette-based web server that exposes A2A endpoints.
  - `start() -> None` - Starts the web server using uvicorn. Raises a `ValueError` if `agent_card` or `task_manager` are not set.
  - `host: str` - The host address the server will bind to.
  - `port: int` - The port the server will listen on.
  - `endpoint: str` - The main API endpoint path for receiving JSON-RPC requests.
  - `task_manager: TaskManager` - The handler responsible for all task-related business logic.
  - `agent_card: AgentCard` - The metadata for the agent, served at `/.well-known/agent.json`.
  
**Usage Examples:**
```python
# main.py
from solace_ai_connector.common.server import A2AServer, InMemoryTaskManager
from solace_ai_connector.common.types import AgentCard

# 1. Define the agent's capabilities and metadata
my_agent_card = AgentCard(
    id="my-awesome-agent-v1",
    name="Awesome Agent",
    version="1.0.0",
    description="An agent that does awesome things.",
    documentation_url="https://example.com/docs",
    supported_tasks=["summarize", "translate"],
    input_modalities=["text/plain"],
    output_modalities=["text/plain"]
)

# 2. Instantiate a task manager (or use your own custom implementation)
# This example uses a basic in-memory manager.
# For a real agent, you would extend InMemoryTaskManager to implement your logic.
class MyAgentTaskManager(InMemoryTaskManager):
    async def on_send_task(self, request):
        # Implement your agent's logic here
        pass
    async def on_send_task_subscribe(self, request):
        # Implement your agent's streaming logic here
        pass

task_manager = MyAgentTaskManager()

# 3. Create and configure the server
server = A2AServer(
    host="127.0.0.1",
    port=8080,
    endpoint="/api/v1/a2a",
    agent_card=my_agent_card,
    task_manager=task_manager
)

# 4. Start the server
if __name__ == "__main__":
    print("Starting A2A Server...")
    server.start()
```

---

### task_manager.py
**Purpose:** Defines the abstract interface for task management and provides a ready-to-use, in-memory implementation. This is the core component for implementing an agent's business logic.
**Import:** `from solace_ai_connector.common.server import TaskManager, InMemoryTaskManager`

**Classes:**
- `TaskManager()` - An abstract base class that defines the interface for handling all A2A task-related operations. Developers must implement these methods in a subclass.
  - `on_get_task(request: GetTaskRequest) -> GetTaskResponse` - Handles a request to retrieve the status and details of a task.
  - `on_cancel_task(request: CancelTaskRequest) -> CancelTaskResponse` - Handles a request to cancel an ongoing task.
  - `on_send_task(request: SendTaskRequest) -> SendTaskResponse` - Handles a standard request-response task submission.
  - `on_send_task_subscribe(request: SendTaskStreamingRequest) -> Union[AsyncIterable[SendTaskStreamingResponse], JSONRPCResponse]` - Handles a task submission that requires a streaming response (SSE).
  - `on_set_task_push_notification(request: SetTaskPushNotificationRequest) -> SetTaskPushNotificationResponse` - Handles a request to configure push notifications for a task.
  - `on_get_task_push_notification(request: GetTaskPushNotificationRequest) -> GetTaskPushNotificationResponse` - Handles a request to retrieve the push notification configuration for a task.
  - `on_resubscribe_to_task(request: TaskResubscriptionRequest) -> Union[AsyncIterable[SendTaskResponse], JSONRPCResponse]` - Handles a request to resubscribe to a streaming task.

- `InMemoryTaskManager()` - A concrete implementation of `TaskManager` that stores tasks and push notification configurations in memory. It provides helper methods to manage task state and SSE subscriptions. It is designed to be extended.
  - `upsert_task(task_send_params: TaskSendParams) -> Task` - Creates a new task or retrieves an existing one by its ID, adding the new message to its history.
  - `update_store(task_id: str, status: TaskStatus, artifacts: list[Artifact]) -> Task` - Updates the status, message history, and artifacts of a specific task.
  - `set_push_notification_info(task_id: str, notification_config: PushNotificationConfig) -> None` - Stores the push notification configuration for a given task.
  - `get_push_notification_info(task_id: str) -> PushNotificationConfig` - Retrieves the push notification configuration for a given task.
  - `has_push_notification_info(task_id: str) -> bool` - Checks if a push notification configuration exists for a task.
  - `setup_sse_consumer(task_id: str, is_resubscribe: bool = False) -> asyncio.Queue` - Creates and registers an `asyncio.Queue` for a new SSE subscriber for a given task.
  - `enqueue_events_for_sse(task_id: str, task_update_event: Any) -> None` - Puts a new event (e.g., `TaskStatusUpdateEvent`) into the queues of all active SSE subscribers for a task.
  - `dequeue_events_for_sse(request_id: str, task_id: str, sse_event_queue: asyncio.Queue) -> AsyncIterable[SendTaskStreamingResponse]` - An async generator that yields events from an SSE queue, wrapping them in `SendTaskStreamingResponse` objects.

**Usage Examples:**
```python
# custom_task_manager.py
import asyncio
from solace_ai_connector.common.server import InMemoryTaskManager
from solace_ai_connector.common.types import (
    SendTaskRequest, SendTaskResponse, Task, TaskStatus, TaskState,
    SendTaskStreamingRequest, SendTaskStreamingResponse, TaskStatusUpdateEvent
)
from typing import AsyncIterable, Union

class MyCustomTaskManager(InMemoryTaskManager):
    # Implement the core logic for a standard task
    async def on_send_task(self, request: SendTaskRequest) -> SendTaskResponse:
        task = await self.upsert_task(request.params)
        print(f"Received task {task.id} with message: {request.params.message.content}")
        
        # Simulate work
        await asyncio.sleep(2)
        
        # Update task status to completed
        final_status = TaskStatus(state=TaskState.COMPLETED)
        await self.update_store(task.id, final_status, [])
        
        return SendTaskResponse(id=request.id, result=task)

    # Implement the core logic for a streaming task
    async def on_send_task_subscribe(
        self, request: SendTaskStreamingRequest
    ) -> Union[AsyncIterable[SendTaskStreamingResponse], JSONRPCResponse]:
        
        await self.upsert_task(request.params)
        sse_queue = await self.setup_sse_consumer(request.params.id)

        # Start the background task processing
        asyncio.create_task(self._process_streaming_task(request.params.id))

        # Return the async generator that will stream responses
        return self.dequeue_events_for_sse(request.id, request.params.id, sse_queue)

    async def _process_streaming_task(self, task_id: str):
        # Simulate streaming work
        for i in range(5):
            await asyncio.sleep(1)
            update = TaskStatusUpdateEvent(
                status=TaskStatus(state=TaskState.IN_PROGRESS),
                message={"content": f"Step {i+1} complete"}
            )
            # Enqueue the update for all subscribers
            await self.enqueue_events_for_sse(task_id, update)
        
        # Send final event
        final_update = TaskStatusUpdateEvent(
            status=TaskStatus(state=TaskState.COMPLETED),
            final=True
        )
        await self.enqueue_events_for_sse(task_id, final_update)
```

---

### utils.py
**Purpose:** Provides common utility functions used within the server, primarily for creating standardized JSON-RPC error responses and performing compatibility checks.
**Import:** `from solace_ai_connector.common.server.utils import are_modalities_compatible, new_incompatible_types_error, new_not_implemented_error`

**Functions:**
- `are_modalities_compatible(server_output_

================================================================================

## Section 13: common/services/providers/providers_llm.txt

**Source file:** `common/services/providers/providers_llm.txt`

## Quick Summary
This directory contains concrete implementations (providers) for the abstract services defined in the parent `services` package. These providers offer specific ways to fulfill service contracts, such as sourcing user identity information from a local file.

## Files Overview
- `__init__.py`: Marks the directory as a Python package.
- `local_file_identity_service.py`: An identity service implementation that reads user data from a local JSON file.

## Developer API Reference

### __init__.py
**Purpose:** Initializes the `providers` package.
**Import:** `from solace_ai_connector.common.services import providers`

This file contains no public classes or functions.

---

### local_file_identity_service.py
**Purpose:** Provides a simple, file-based identity service that reads user profiles from a local JSON file. It's ideal for development, testing, or small-scale deployments where a full-fledged identity provider is not available.
**Import:** `from solace_ai_connector.common.services.providers.local_file_identity_service import LocalFileIdentityService`

**Classes:**
- `LocalFileIdentityService(config: Dict[str, Any])` - An identity service that sources user data from a local JSON file. The `config` dictionary must contain a `file_path` key.
  - `async get_user_profile(auth_claims: Dict[str, Any]) -> Optional[Dict[str, Any]]` - Looks up a user profile from the in-memory index. The lookup is performed using the `lookup_key` (configured during initialization) present in the `auth_claims` dictionary.
  - `async search_users(query: str, limit: int = 10) -> List[Dict[str, Any]]` - Performs a simple, case-insensitive search across user names and emails. Returns a list of matching user profiles.
  - `file_path: str` - The path to the JSON file containing the user data.
  - `lookup_key: str` - The key within the user profile objects and `auth_claims` used to identify a user. Defaults to `"id"`.
  - `all_users: List[Dict[str, Any]]` - The complete list of all user profiles loaded from the file.
  - `user_index: Dict[str, Dict[str, Any]]` - An in-memory dictionary mapping the `lookup_key` value to the corresponding user profile for fast lookups.

**Usage Examples:**
```python
import asyncio
import json
import os
from typing import Dict, Any, Optional, List

# Assume this is the identity service class from the file
from solace_ai_connector.common.services.providers.local_file_identity_service import LocalFileIdentityService

# --- Setup: Create a dummy users.json for the example ---
users_data = [
  {
    "id": "jdoe",
    "email": "jane.doe@example.com",
    "name": "Jane Doe",
    "title": "Senior Engineer",
    "manager_id": "ssmith"
  },
  {
    "id": "ssmith",
    "email": "sam.smith@example.com",
    "name": "Sam Smith",
    "title": "Engineering Manager",
    "manager_id": None
  }
]
file_path = "users.json"
with open(file_path, "w") as f:
    json.dump(users_data, f)
# --- End Setup ---


async def main():
    # 1. Configure the service
    # The 'file_path' is required. 'lookup_key' is optional (defaults to 'id').
    config = {
        "file_path": file_path,
        "lookup_key": "id"
    }

    # 2. Initialize the service
    identity_service = LocalFileIdentityService(config)
    print(f"Service initialized. Loaded {len(identity_service.all_users)} users.")

    # 3. Get a specific user profile
    print("\n--- Getting user profile for id 'jdoe' ---")
    auth_claims = {"id": "jdoe"}
    profile = await identity_service.get_user_profile(auth_claims)
    if profile:
        print(f"Found profile: {profile}")
    else:
        print("Profile not found.")

    # 4. Search for users by name
    print("\n--- Searching for users with 'sam' in their name ---")
    search_results = await identity_service.search_users(query="sam", limit=5)
    print(f"Found {len(search_results)} user(s): {search_results}")

    # 5. Handle a case where the user is not found
    print("\n--- Getting user profile for non-existent id 'nobody' ---")
    not_found_profile = await identity_service.get_user_profile({"id": "nobody"})
    print(f"Profile for 'nobody': {not_found_profile}")


if __name__ == "__main__":
    asyncio.run(main())
    # Clean up the dummy file
    os.remove(file_path)

# Expected output:
#
# Service initialized. Loaded 2 users.
#
# --- Getting user profile for id 'jdoe' ---
# Found profile: {'id': 'jdoe', 'email': 'jane.doe@example.com', 'name': 'Jane Doe', 'title': 'Senior Engineer', 'manager_id': 'ssmith'}
#
# --- Searching for users with 'sam' in their name ---
# Found 1 user(s): [{'id': 'ssmith', 'name': 'Sam Smith', 'email': 'sam.smith@example.com', 'title': 'Engineering Manager'}]
#
# --- Getting user profile for non-existent id 'nobody' ---
# Profile for 'nobody': None
```

================================================================================

## Section 14: common/services/services_llm.txt

**Source file:** `common/services/services_llm.txt`

## Quick Summary
The `services` directory provides a modular and extensible framework for integrating external data sources related to identity and employee information into the Solace AI Connector. It is built on a provider pattern, defining abstract base classes (`BaseIdentityService`, `BaseEmployeeService`) that establish a clear contract for what data and functionality a service must provide.

The core architecture revolves around factory functions (`create_identity_service`, `create_employee_service`) that instantiate specific service providers based on a configuration dictionary. This allows the application to remain decoupled from the concrete implementations. Providers can be either built-in (like the file-based identity service located in the `providers/` subdirectory) or dynamically loaded as external plugins, making the system highly flexible and easy to extend.

## Files and Subdirectories Overview
- **Direct files:**
  - `__init__.py`: Marks the directory as a Python package.
  - `employee_service.py`: Defines the abstract contract and factory for employee data services.
  - `identity_service.py`: Defines the abstract contract and factory for user identity services.
- **Subdirectories:**
  - `providers/`: Contains concrete implementations of the service contracts, such as a file-based identity provider.

## Developer API Reference

### Direct Files

#### employee_service.py
**Purpose:** Defines the abstract base class (`BaseEmployeeService`) that all employee service providers must implement, and a factory function (`create_employee_service`) to instantiate them. It enforces a canonical schema for employee data to ensure consistency across different providers.
**Import:** `from solace_ai_connector.common.services import BaseEmployeeService, create_employee_service`

**Classes/Functions/Constants:**
- **`class BaseEmployeeService(ABC)`**: The abstract base class for employee service providers.
    - **`__init__(self, config: Dict[str, Any])`**: Initializes the service, setting up configuration and an optional in-memory cache.
    - **`async def get_employee_dataframe(self) -> pd.DataFrame`**: (Abstract) Returns the entire employee directory as a pandas DataFrame.
    - **`async def get_employee_profile(self, employee_id: str) -> Optional[Dict[str, Any]]`**: (Abstract) Fetches the profile for a single employee, conforming to the canonical schema.
    - **`async def get_time_off_data(self, employee_id: str) -> List[Dict[str, Any]]`**: (Abstract) Retrieves a list of time-off entries for an employee.
    - **`async def get_employee_profile_picture(self, employee_id: str) -> Optional[str]`**: (Abstract) Fetches an employee's profile picture as a data URI string.
- **`def create_employee_service(config: Optional[Dict[str, Any]]) -> Optional[BaseEmployeeService]`**: A factory function that dynamically loads and instantiates an employee service provider based on the `type` specified in the configuration. It primarily uses Python's entry points to find and load external plugins.

#### identity_service.py
**Purpose:** Defines the abstract base class (`BaseIdentityService`) for identity providers and a factory function (`create_identity_service`) to create instances of them. This service is used for user lookups and profile enrichment.
**Import:** `from solace_ai_connector.common.services import BaseIdentityService, create_identity_service`

**Classes/Functions/Constants:**
- **`class BaseIdentityService(ABC)`**: The abstract base class for identity service providers.
    - **`__init__(self, config: Dict[str, Any])`**: Initializes the service, setting up configuration and an optional in-memory cache.
    - **`async def get_user_profile(self, auth_claims: Dict[str, Any]) -> Optional[Dict[str, Any]]`**: (Abstract) Fetches additional profile details for an authenticated user based on claims.
    - **`async def search_users(self, query: str, limit: int = 10) -> List[Dict[str, Any]]`**: (Abstract) Searches for users based on a query string (e.g., for autocomplete).
- **`def create_identity_service(config: Optional[Dict[str, Any]]) -> Optional[BaseIdentityService]`**: A factory function that instantiates an identity service provider. It has special handling for the built-in `local_file` provider and uses Python entry points for all other provider types.

### Subdirectory APIs

#### providers/
**Purpose:** This subdirectory contains concrete implementations of the abstract service classes. It ships with a built-in provider for the `IdentityService` that is useful for development and testing.
**Key Exports:** `LocalFileIdentityService`
**Import Examples:**
```python
# Typically, you would use the factory function.
# But for direct instantiation (e.g., in tests), you can do this:
from solace_ai_connector.common.services.providers import LocalFileIdentityService
```

## Complete Usage Guide
The following examples demonstrate how to use the services framework, from basic instantiation using factories to creating custom providers.

### 1. How to Use the Service Factories (Recommended)
The factories are the primary way to create and use services. They abstract away the specific implementation details.

**Example: Creating a File-Based Identity Service and a Plugin-Based Employee Service**

```python
import asyncio
from solace_ai_connector.common.services import create_identity_service, create_employee_service

# Assume you have a users.json file for the identity service
# and a plugin installed for the employee service.

async def main():
    # --- Identity Service Example (using a built-in provider) ---
    identity_config = {
        "type": "local_file",
        "file_path": "path/to/your/users.json",
        "lookup_key": "email",  # Key to use for lookups from auth_claims
        "cache_ttl_seconds": 3600
    }
    identity_service = create_identity_service(identity_config)

    if identity_service:
        print("Identity Service created.")
        # Fetch a user profile
        auth_claims = {"email": "jane.doe@example.com"}
        user_profile = await identity_service.get_user_profile(auth_claims)
        print(f"User Profile: {user_profile}")

        # Search for users
        search_results = await identity_service.search_users("Jane")
        print(f"Search Results: {search_results}")

    # --- Employee Service Example (using an external plugin) ---
    # The 'type' must match the name of a registered plugin entry point.
    employee_config = {
        "type": "bamboohr_plugin",
        "api_key": "your-secret-api-key",
        "subdomain": "your-company",
        "cache_ttl_seconds": 7200
    }
    employee_service = create_employee_service(employee_config)

    if employee_service:
        print("\nEmployee Service created.")
        # Get a detailed employee profile
        employee_profile = await employee_service.get_employee_profile("jane.doe@example.com")
        print(f"Employee Profile: {employee_profile}")

        # Get time off data
        time_off = await employee_service.get_time_off_data("jane.doe@example.com")
        print(f"Time Off Data: {time_off}")

# To run this example:
# asyncio.run(main())
```

### 2. How to Use Functionality from Subdirectories
While factories are preferred, you can instantiate providers from the `providers/` directory directly. This is useful for testing or when you know you will always use a specific built-in provider.

**Example: Direct Instantiation of `LocalFileIdentityService`**

```python
import asyncio
from solace_ai_connector.common.services.providers import LocalFileIdentityService

async def main():
    # Configuration does not need a 'type' key for direct instantiation
    config = {
        "file_path": "path/to/your/users.json",
        "lookup_key": "id"
    }

    # Instantiate the class directly
    local_service = LocalFileIdentityService(config)
    print("LocalFileIdentityService

================================================================================

## Section 15: common/utils/embeds/embeds_llm.txt

**Source file:** `common/utils/embeds/embeds_llm.txt`

Here is the developer guide for the `embeds` directory.

## Quick Summary
The `embeds` directory provides a system for finding, parsing, and resolving embedded expressions within strings. These expressions, denoted by `«...»`, can represent dynamic values like mathematical calculations, datetimes, or content from stored artifacts. The system supports multi-step data transformation pipelines on artifact content, recursive embed resolution, and safety features like depth and size limits. It is a core component for dynamic content generation and data processing.

## Files Overview
- `__init__.py`: Exports the primary public functions and constants for easy access.
- `constants.py`: Defines the syntax (delimiters, separators), regular expressions, and type classifications for embeds.
- `converter.py`: Provides functions for converting data between different formats (e.g., bytes, string, JSON) and for serializing data into a final string representation.
- `evaluators.py`: Contains the specific logic for evaluating simple embed types like `math`, `datetime`, and `uuid`.
- `modifiers.py`: Implements a library of data transformation functions (e.g., `jsonpath`, `slice_rows`, `grep`) that can be chained together.
- `resolver.py`: The core engine that orchestrates the entire embed resolution process, including handling modifier chains and recursion.
- `types.py`: Defines the `DataFormat` enum used to track data types during transformations.

## Developer API Reference

### __init__.py
**Purpose:** This module serves as the main public entry point for the `embeds` package, exporting the most commonly used functions and constants from the other modules. Developers should typically import from here.

**Import:** `from src.solace_agent_mesh.common.utils.embeds import resolve_embeds_recursively_in_string, evaluate_embed, EMBED_REGEX`

*(Note: Detailed documentation is available under each source file's section.)*

**Classes:**
- None

**Functions:**
- `evaluate_embed(...)`: Evaluates a single, parsed embed expression.
- `resolve_embeds_in_string(...)`: Resolves embeds in a string for a single pass (non-recursive).
- `resolve_embeds_recursively_in_string(...)`: Recursively finds and resolves all embeds in a string, respecting depth and size limits.

**Constants/Variables:**
- `EMBED_DELIMITER_OPEN: str`: The opening delimiter for an embed (`«`).
- `EMBED_DELIMITER_CLOSE: str`: The closing delimiter for an embed (`»`).
- `EMBED_TYPE_SEPARATOR: str`: The separator between an embed's type and its expression (`:`).
- `EMBED_FORMAT_SEPARATOR: str`: The separator for an optional format specifier (`|`).
- `EMBED_CHAIN_DELIMITER: str`: The separator for modifier steps in an `artifact_content` chain (`>>>`).
- `EMBED_REGEX: re.Pattern`: The compiled regular expression used to find embeds.
- `EARLY_EMBED_TYPES: Set[str]`: A set of embed types that are resolved in an initial pass.
- `LATE_EMBED_TYPES: Set[str]`: A set of embed types (like `artifact_content`) resolved in a subsequent pass.

---
### constants.py
**Purpose:** This file defines all the static constants that govern the syntax and classification of embeds. This includes delimiters, separators, the master regular expression for parsing, and sets that categorize embed types for phased resolution.

**Import:** `from src.solace_agent_mesh.common.utils.embeds.constants import EMBED_REGEX, EARLY_EMBED_TYPES`

**Classes:**
- None

**Functions:**
- None

**Constants/Variables:**
- `EMBED_DELIMITER_OPEN: str`: The character that marks the beginning of an embed (`«`).
- `EMBED_DELIMITER_CLOSE: str`: The character that marks the end of an embed (`»`).
- `EMBED_TYPE_SEPARATOR: str`: The character separating the embed type from its expression (`:`).
- `EMBED_FORMAT_SEPARATOR: str`: The character separating an expression from its optional format specifier (`|`).
- `EMBED_CHAIN_DELIMITER: str`: The string separating transformation steps in an `artifact_content` embed (`>>>`).
- `EMBED_REGEX: re.Pattern`: A compiled regular expression to find and capture the `type`, `expression`, and optional `format` from an embed string.
- `EARLY_EMBED_TYPES: Set[str]`: A set of embed types (`math`, `datetime`, etc.) that are resolved first, as they are generally simple, self-contained, and do not involve recursion.
- `LATE_EMBED_TYPES: Set[str]`: A set of embed types (`artifact_content`) that are resolved later, as they can be complex, involve I/O, and may contain further embeds that require recursive resolution.
- `TEXT_CONTAINER_MIME_TYPES: Set[str]`: A set of MIME types that are considered to contain text and can be safely decoded to a string.

**Usage Examples:**
```python
import re
from src.solace_agent_mesh.common.utils.embeds.constants import EMBED_REGEX

text = "The price is «math:10 * 1.15 | .2f» and the ID is «uuid:new»."

for match in EMBED_REGEX.finditer(text):
    embed_type = match.group(1)
    expression = match.group(2)
    format_spec = match.group(3) # This will be None if not present
    print(f"Type: {embed_type}, Expression: '{expression}', Format: '{format_spec}'")

# Expected Output:
# Type: math, Expression: '10 * 1.15 ', Format: ' .2f'
# Type: uuid, Expression: 'new', Format: 'None'
```

---
### converter.py
**Purpose:** This file provides the core logic for data conversion and serialization. It can transform data between different `DataFormat` representations (e.g., `BYTES` to `STRING`, `STRING` to `LIST_OF_DICTS`) and serialize any format into a final string representation (e.g., `json`, `csv`, `datauri`).

**Import:** `from src.solace_agent_mesh.common.utils.embeds.converter import convert_data, serialize_data`

**Classes:**
- None

**Functions:**
- `convert_data(current_data: Any, current_format: Optional[DataFormat], target_format: DataFormat, log_id: str = "[Converter]", original_mime_type: Optional[str] = None) -> Tuple[Any, DataFormat, Optional[str]]`: Converts data from a source format to a target format. It uses `original_mime_type` as a hint for parsing (e.g., knowing that a string is JSON or CSV). Returns a tuple of `(converted_data, resulting_format, error_message)`.
- `serialize_data(data: Any, data_format: Optional[DataFormat], target_string_format: Optional[str], original_mime_type: Optional[str], log_id: str = "[Serializer]") -> Tuple[str, Optional[str]]`: Serializes data from any `DataFormat` into a final string. `target_string_format` can be a keyword like `"json"`, `"csv"`, `"datauri"`, or a Python format specifier for numbers (e.g., `".2f"`). Returns a tuple of `(serialized_string, error_message)`.

**Constants/Variables:**
- None

**Usage Examples:**
```python
from src.solace_agent_mesh.common.utils.embeds.converter import convert_data, serialize_data
from src.solace_agent_mesh.common.utils.embeds.types import DataFormat

# Example 1: Convert CSV bytes to a list of dictionaries
csv_bytes = b"id,name\n1,Alice\n2,Bob"
list_of_dicts, new_format, err = convert_data(
    current_data=csv_bytes,
    current_format=DataFormat.BYTES,
    target_format=DataFormat.LIST_OF_DICTS,
    original_mime_type="text/csv"
)
if not err:
    print(f"Converted data: {list_of_dicts}")
    # Converted data: [{'id': '1', 'name': 'Alice'}, {'id': '2', 'name': 'Bob'}]

# Example 2: Serialize the list of dictionaries back to a pretty JSON string
json_string, err = serialize_data(
    data=list_of_dicts,
    data_format=DataFormat.LIST_OF_DICTS,
    target_string_format="json_pretty",
    original_mime_type=None
)
if not err:
    print(f"Serialized JSON:\n{json_string}")

================================================================================

## Section 16: common/utils/utils_llm.txt

**Source file:** `common/utils/utils_llm.txt`

Here is the comprehensive developer guide for the `utils` directory.

## Quick Summary
The `utils` directory provides a collection of essential, cross-cutting utilities for the Solace AI Connector. Its purpose is to offer robust, reusable solutions for common application needs, including caching, platform compatibility, secure communication, logging, and dynamic content generation.

The architecture consists of standalone utility files for specific tasks and a more complex, self-contained subdirectory for advanced functionality. Direct files provide services like a thread-safe in-memory cache (`in_memory_cache.py`), JWT-based authentication for push notifications (`push_notification_auth.py`), custom logging formatters (`log_formatters.py`), and a critical patch for asyncio on macOS (`asyncio_macos_fix.py`).

The `embeds` subdirectory provides a powerful system for finding, parsing, and resolving dynamic expressions embedded within strings. These utilities are designed to work together. For instance, a request handler might use `mime_helpers` to validate content type, use the `embeds` system to process the content, and then store the result in the `InMemoryCache` to optimize future requests.

## Files and Subdirectories Overview
- **Direct files:**
    - `__init__.py`: Exposes key utility functions from the package for convenient access.
    - `asyncio_macos_fix.py`: Automatically applies a patch to fix asyncio subprocess issues on macOS.
    - `in_memory_cache.py`: Implements a thread-safe, singleton in-memory cache with TTL support.
    - `log_formatters.py`: Provides custom logging formatters, such as a Datadog-compatible JSON formatter.
    - `mime_helpers.py`: Contains helper functions to classify and identify text-based MIME types.
    - `push_notification_auth.py`: Implements JWT-based authentication for sending and receiving push notifications.

- **Subdirectories:**
    - `embeds/`: Provides a comprehensive system for processing embedded dynamic expressions (e.g., math, datetimes, artifact content).

## Developer API Reference

### Direct Files

#### __init__.py
**Purpose:** Serves as the main entry point for the `utils` package, exporting the most common utility functions for easy importing.
**Import:** `from solace_ai_connector.common.utils import is_text_based_mime_type`

**Classes/Functions/Constants:**
*   `is_text_based_mime_type(mime_type: Optional[str]) -> bool`: Checks if a given MIME type is considered text-based.

#### asyncio_macos_fix.py
**Purpose:** Provides a targeted, automatic fix for a `NotImplementedError` that occurs when creating subprocesses with asyncio on macOS. This module is imported for its side effects and should be loaded early in the application's lifecycle.
**Import:** `from solace_ai_connector.common.utils import asyncio_macos_fix` (Importing the module is sufficient to apply the patch).

**Classes/Functions/Constants:**
*   `ensure_asyncio_compatibility() -> bool`: The core function that applies the patch. It is called automatically when the module is first imported.

#### in_memory_cache.py
**Purpose:** Provides a simple, thread-safe, in-memory cache implemented as a singleton. It's useful for storing frequently accessed data with an optional time-to-live (TTL).
**Import:** `from solace_ai_connector.common.utils.in_memory_cache import InMemoryCache`

**Classes/Functions/Constants:**
*   **`InMemoryCache`**: A singleton class for caching.
    *   `set(self, key: str, value: Any, ttl: Optional[int] = None) -> None`: Sets a key-value pair with an optional TTL in seconds.
    *   `get(self, key: str, default: Any = None) -> Any`: Retrieves a value by its key, returning a default if the key is not found or has expired.
    *   `delete(self, key: str) -> bool`: Deletes a key-value pair from the cache.
    *   `clear(self) -> bool`: Removes all items from the cache.

#### log_formatters.py
**Purpose:** Contains custom logging formatters to structure log output for specific platforms, such as Datadog.
**Import:** `from solace_ai_connector.common.utils.log_formatters import DatadogJsonFormatter`

**Classes/Functions/Constants:**
*   **`DatadogJsonFormatter(logging.Formatter)`**: A formatter that outputs log records as a JSON string, compatible with Datadog's standard log attributes. It automatically includes tracing information (`dd.trace_id`, `dd.span_id`) if available.

#### mime_helpers.py
**Purpose:** Provides utilities for handling and classifying MIME types, with a focus on identifying which types represent text-based content.
**Import:** `from solace_ai_connector.common.utils.mime_helpers import is_text_based_mime_type, TEXT_CONTAINER_MIME_TYPES`

**Classes/Functions/Constants:**
*   `is_text_based_mime_type(mime_type: Optional[str]) -> bool`: Returns `True` if the MIME type starts with `text/` or is in the list of known text-based application types (like `application/json`).
*   `TEXT_CONTAINER_MIME_TYPES: Set[str]`: A set of non-`text/*` MIME types that are considered to contain text (e.g., `application/json`, `application/yaml`).

#### push_notification_auth.py
**Purpose:**

================================================================================

## Section 17: core_a2a/core_a2a_llm.txt

**Source file:** `core_a2a/core_a2a_llm.txt`

# DEVELOPER GUIDE: core_a2a

## Quick Summary
The `core_a2a` directory provides a reusable service layer for core Agent-to-Agent (A2A) interactions. It handles task submission (both regular and streaming), task cancellation, and agent discovery processing while being decoupled from specific gateway implementations and SAC messaging details.

## Files Overview
- `__init__.py` - Package initialization file for the core A2A service layer
- `service.py` - Main service class that encapsulates A2A protocol logic and agent registry operations

## Developer API Reference

### __init__.py
**Purpose:** Package initialization for the core A2A service layer
**Import:** `import core_a2a`

No public classes, functions, or constants defined.

### service.py
**Purpose:** Provides the main CoreA2AService class for handling A2A protocol operations
**Import:** `from core_a2a.service import CoreA2AService`

**Classes:**
- `CoreA2AService(agent_registry: AgentRegistry, namespace: str)` - Main service class for A2A operations
  - `submit_task(agent_name: str, a2a_message: A2AMessage, session_id: str, client_id: str, reply_to_topic: str, user_id: str = "default_user", a2a_user_scopes: Optional[List[str]] = None, metadata_override: Optional[Dict[str, Any]] = None) -> Tuple[str, Dict, Dict]` - Constructs topic, payload, and user properties for non-streaming task requests
  - `submit_streaming_task(agent_name: str, a2a_message: A2AMessage, session_id: str, client_id: str, reply_to_topic: str, status_to_topic: str, user_id: str = "default_user", a2a_user_scopes: Optional[List[str]] = None, metadata_override: Optional[Dict[str, Any]] = None) -> Tuple[str, Dict, Dict]` - Constructs topic, payload, and user properties for streaming task requests
  - `cancel_task(agent_name: str, task_id: str, client_id: str, user_id: str = "default_user") -> Tuple[str, Dict, Dict]` - Constructs topic, payload, and user properties for task cancellation
  - `get_agent(agent_name: str) -> Optional[AgentCard]` - Retrieves a specific agent card by name from the registry
  - `get_all_agents() -> List[AgentCard]` - Retrieves all currently discovered agent cards from the registry
  - `process_discovery_message(agent_card: AgentCard)` - Processes an incoming agent card discovery message
  - `agent_registry: AgentRegistry` - The shared agent registry instance
  - `namespace: str` - The A2A namespace string
  - `log_identifier: str` - Identifier used for logging

**Functions:**
None (all functionality is encapsulated in the CoreA2AService class)

**Constants/Variables:**
None

**Usage Examples:**
```python
# Import required dependencies
from core_a2a.service import CoreA2AService
from common.agent_registry import AgentRegistry
from common.types import A2AMessage, AgentCard

# Initialize the service
agent_registry = AgentRegistry()
namespace = "my_NAMESPACE"
service = CoreA2AService(agent_registry, namespace)

# Submit a regular task
message = A2AMessage(parts=[{"type": "text", "content": "Hello"}])
topic, payload, user_props = service.submit_task(
    agent_name="my_agent",
    a2a_message=message,
    session_id="session_123",
    client_id="client_456",
    reply_to_topic="responses/client_456",
    user_id="user_789"
)

# Submit a streaming task
topic, payload, user_props = service.submit_streaming_task(
    agent_name="my_agent",
    a2a_message=message,
    session_id="session_123",
    client_id="client_456",
    reply_to_topic="responses/client_456",
    status_to_topic="status/client_456",
    user_id="user_789"
)

# Cancel a task
topic, payload, user_props = service.cancel_task(
    agent_name="my_agent",
    task_id="task-abc123",
    client_id="client_456"
)

# Get agent information
agent = service.get_agent("my_agent")
all_agents = service.get_all_agents()

# Process discovery message
agent_card = AgentCard(name="new_agent", description="A new agent")
service.process_discovery_message(agent_card)
```

================================================================================

## Section 18: gateway/base/base_llm.txt

**Source file:** `gateway/base/base_llm.txt`

## Quick Summary
The `base` directory provides the foundational, abstract classes for building Gateway implementations within the Solace AI Connector. It establishes a framework for handling common gateway tasks such as application configuration, Solace broker integration, A2A (Agent-to-Agent) message protocol handling, and managing the lifecycle of requests from external platforms. Developers should subclass `BaseGatewayApp` and `BaseGatewayComponent` to create a new gateway.

## Files Overview
- `__init__.py`: Marks the directory as a Python package.
- `app.py`: Contains the base application class (`BaseGatewayApp`) that handles configuration, schema merging, and broker setup.
- `component.py`: Contains the core logic class (`BaseGatewayComponent`) for processing A2A messages and integrating with external platforms.
- `task_context.py`: Provides a thread-safe manager for mapping A2A task IDs to their original request context.

## Developer API Reference

### __init__.py
**Purpose:** Initializes the `gateway.base` Python package.
**Import:** `from gateway.base import ...`

---

### app.py
**Purpose:** Provides the base application class for gateway implementations. It automates configuration schema merging, Solace broker setup (including topic subscriptions and queue creation), and component instantiation.
**Import:** `from gateway.base.app import BaseGatewayApp, BaseGatewayComponent`

**Classes:**
- `BaseGatewayComponent(ComponentBase)` - A base class marker for gateway components. Subclasses of `BaseGatewayComponent` from `component.py` inherit from this.
- `BaseGatewayApp(app_info: Dict[str, Any], **kwargs)` - The main application class to be subclassed for a new gateway.
  - `_get_gateway_component_class(self) -> Type[BaseGatewayComponent]` - **[Abstract Method]** Must be implemented by subclasses to return the specific gateway component class that will handle the core logic.
  - `namespace: str` - The absolute topic prefix for A2A communication (e.g., 'myorg/dev').
  - `gateway_id: str` - The unique ID for this gateway instance. Auto-generated if not provided.
  - `artifact_service_config: Dict` - Configuration for the shared ADK Artifact Service.
  - `enable_embed_resolution: bool` - Flag to enable or disable late-stage 'artifact_content' embed resolution.
  - `gateway_max_artifact_resolve_size_bytes: int` - Maximum size for resolving individual or recursively embedded artifacts.
  - `gateway_recursive_embed_depth: int` - Maximum depth for recursively resolving 'artifact_content' embeds.

**Constants/Variables:**
- `BASE_GATEWAY_APP_SCHEMA: Dict[str, List[Dict[str, Any]]]` - The base configuration schema dictionary that is automatically merged with subclass-specific parameters.
- `SPECIFIC_APP_SCHEMA_PARAMS_ATTRIBUTE_NAME: str` - The class attribute name (`"SPECIFIC_APP_SCHEMA_PARAMS"`) that subclasses should use to define their own configuration parameters.

**Usage Examples:**
```python
# In your custom gateway's app.py

from typing import Type, List, Dict, Any
from gateway.base.app import BaseGatewayApp
from .component import MyGatewayComponent # Your custom component

class MyGatewayApp(BaseGatewayApp):
    """
    A custom gateway application for My Platform.
    """
    # Define additional configuration parameters specific to this gateway
    SPECIFIC_APP_SCHEMA_PARAMS: List[Dict[str, Any]] = [
        {
            "name": "my_platform_api_key",
            "required": True,
            "type": "string",
            "description": "API key for connecting to My Platform."
        }
    ]

    def _get_gateway_component_class(self) -> Type[MyGatewayComponent]:
        """
        Returns our custom component class.
        """
        return MyGatewayComponent

# To run this app (typically via a YAML configuration file):
# app_config = {
#     "name": "my-gateway-app",
#     "app_class": MyGatewayApp,
#     "app_config": {
#         "namespace": "myorg/prod",
#         "gateway_id": "my-gateway-instance-01",
#         "artifact_service": {
#             "type": "local_file",
#             "base_path": "/data/artifacts"
#         },
#         "my_platform_api_key": "secret-key-here"
#     }
# }
# app = MyGatewayApp(app_info=app_config)
# app.run()
```

---

### component.py
**Purpose:** Provides the abstract base class for gateway components. This class contains the core logic for handling the A2A protocol, managing services (identity, artifacts), and defining the interface for interaction with an external platform (e.g., a web server, a chat application).
**Import:** `from gateway.base.component import BaseGatewayComponent`

**Classes:**
- `BaseGatewayComponent(**kwargs: Any)` - The abstract base class for gateway components. Developers must subclass this and implement the abstract methods.
  - **Public Methods:**
    - `publish_a2a_message(self, topic: str, payload: Dict, user_properties: Optional[Dict] = None) -> None` - Publishes a message to the Solace broker for A2A communication.
    - `authenticate_and_enrich_user(self, external_event_data: Any) -> Optional[Dict[str, Any]]` - Orchestrates the full user authentication and identity enrichment flow by calling `_extract_initial_claims` and the configured Identity Service.
    - `submit_a2a_task(self, target_agent_name: str, a2a_parts: List[A2APart], external_request_context: Dict[str, Any], user_identity: Any, is_streaming: bool = True, api_version: str = "v2") -> str` - Submits a task to a target agent, handling user configuration resolution, message creation, and context storage. Returns the generated `task_id`.
    - `run(self) -> None` - Starts the component's asynchronous operations, including the message processor loop and the external platform listener.
    - `cleanup(self) -> None` - Cleans up all resources, stops listeners, and shuts down background threads.
  - **Abstract Methods (Must be Implemented by Subclasses):**
    - `_extract_initial_claims(self, external_event_data: Any) -> Optional[Dict[str, Any]]` - Extracts primary identity claims (e.g., user ID) from a platform-specific event. Must return a dict with an 'id' key, or None if auth fails.
    - `_start_listener(self) -> None` - Starts the listener for the external platform (e.g., start a web server, connect to a WebSocket).
    - `_stop_listener(self) -> None` - Stops the listener for the external platform.
    - `_translate_external_input(self, external_event: Any) -> Tuple[str, List[A2APart], Dict[str, Any]]` - Translates an incoming event from the external platform into a format the A2A protocol understands: `(target_agent_name, list_of_a2a_parts, external_request_context)`.
    - `_send_update_to_external(self, external_request_context: Dict[str, Any], event_data: Union[TaskStatusUpdateEvent, TaskArtifactUpdateEvent], is_final_chunk_of_update: bool) -> None` - Sends a streaming update (e.g., a status message or an artifact) back to the external platform.
    - `_send_final_response_to_external(self, external_request_context: Dict[str, Any], task_data: Task) -> None` - Sends the final, complete response of a task back to the external platform.
    - `_send_error_to_external(self, external_request_context: Dict[str, Any], error_data: JSONRPCError) -> None` - Sends an error message back to the external platform.

**Usage Examples:**
```python
# In your custom gateway's component.py

from typing import Any, Dict, List, Optional, Tuple, Union
from gateway.base.component import BaseGatewayComponent
from ...common.types import (
    Part as A2APart, TextPart, Task, TaskStatusUpdateEvent,
    TaskArtifactUpdateEvent, JSONRPCError
)

class MyGatewayComponent(BaseGatewayComponent):
    # This is a simplified example. A real implementation would
    #

================================================================================

## Section 19: gateway/gateway_llm.txt

**Source file:** `gateway/gateway_llm.txt`

Here is the comprehensive developer guide for the `gateway` directory.

## Quick Summary
The `gateway` directory provides a comprehensive framework for building gateway implementations that bridge external platforms with the Solace AI Connector's A2A (Agent-to-Agent) messaging system. The architecture consists of a foundational base framework and three specialized gateway implementations: HTTP/SSE for web interfaces, Slack for team collaboration, and Webhook for external system integration. All gateways share common patterns for authentication, message translation, and real-time communication while providing platform-specific features.

## Files and Subdirectories Overview
- **Direct files:**
  - `__init__.py`: Marks the directory as a Python package.
- **Subdirectories:**
  - `base/`: Foundational classes and utilities for building all gateway implementations.
  - `http_sse/`: A complete HTTP/SSE gateway with a FastAPI web server for real-time web UI backends.
  - `slack/`: A gateway for integrating with the Slack collaboration platform.
  - `webhook/`: A universal webhook gateway for receiving HTTP requests from external systems.

## Developer API Reference

### Direct Files

#### __init__.py
**Purpose:** Initializes the `gateway` module, making it a Python package.
**Import:** `from gateway import ...`

**Classes/Functions/Constants:**
This file is empty and contains no direct exports.

### Subdirectory APIs

#### base/
**Purpose:** Provides the foundational, abstract classes for building all Gateway implementations. It establishes a framework for configuration, A2A message handling, and managing the lifecycle of requests from external platforms.
**Key Exports:** `BaseGatewayApp`, `BaseGatewayComponent`, `TaskContextManager`
**Import Examples:**
```python
from gateway.base.app import BaseGatewayApp
from gateway.base.component import BaseGatewayComponent
from gateway.base.task_context import TaskContextManager
```

**Key Modules:**

*   **`app.py`**:
    *   **`BaseGatewayApp`**: The main application class to be subclassed for a new gateway. It automates configuration schema merging, Solace broker setup, and component instantiation.
        *   `_get_gateway_component_class(self)`: **[Abstract Method]** Subclasses must implement this to return their specific gateway component class.

*   **`component.py`**:
    *   **`BaseGatewayComponent`**: The abstract base class for gateway logic. Subclasses implement the abstract methods to define how the gateway interacts with its specific external platform.
        *   **Public Methods**:
            *   `submit_a2a_task(...)`: The primary method for submitting a task to an agent on behalf of an external user.
            *   `publish_a2a_message(...)`: A lower-level method to publish any message to the A2A message bus.
        *   **Abstract Methods to Implement**:
            *   `_extract_initial_claims(self, external_event_data)`: Extracts user identity from a platform-specific event.
            *   `_start_listener(self)` / `_stop_listener(self)`: Manages the lifecycle of the external platform listener (e.g., a web server).
            *   `_translate_external_input(self, external_event)`: Translates an incoming event from the external platform into the A2A protocol format.
            *   `_send_update_to_external(...)`: Sends a streaming update back to the external platform.
            *   `_send_final_response_to_external(...)`: Sends the final task result back to the external platform.
            *   `_send_error_to_external(...)`: Sends an error message back to the external platform.

*   **`task_context.py`**:
    *   **`TaskContextManager`**: A thread-safe dictionary-like class for mapping A2A task IDs to the original request context from the external platform. This is crucial for routing responses back to the correct user/channel/thread.

#### http_sse/
**Purpose:** Implements a complete HTTP/SSE gateway to serve a web-based user interface, bridging web protocols with the backend A2A messaging fabric.
**Key Exports:** `WebUIBackendApp`, `WebUIBackendComponent`, `SSEManager`, `SessionManager`, and various dependency injectors.
**Import Examples:**
```python
from gateway.http_sse.app import WebUIBackendApp
from gateway.http_sse.component import WebUIBackendComponent
from gateway.http_sse.sse_manager import SSEManager
from gateway.http_sse.session_manager import SessionManager
from gateway.http_sse.dependencies import get_agent_service, get_task_service, get_user_id
```

**Key Modules & Exports:**

*   **`app.py`**:
    *   **`WebUIBackendApp`**: The main SAC App class that defines the configuration schema and launches the `WebUIBackendComponent`.
*   **`component.py`**:
    *   **`WebUIBackendComponent`**: The core component that hosts the FastAPI server, manages shared state, and implements the A2A translation logic for HTTP requests.
*   **`session_manager.py`**:
    *   **`SessionManager`**: Manages web user sessions, creating and tracking unique A2A client and session IDs from HTTP requests.
*   **`sse_manager.py`**:
    *   **`SSEManager`**: Manages Server-Sent Event (SSE) connections, allowing for real-time, streaming updates to be pushed from the server to connected web clients.
*   **`dependencies.py`**:
    *   Provides FastAPI dependency injectors for giving API routers safe access to shared resources (e.g., `get_agent_service`, `get_task_service`, `get_sac_component`).
*   **`services/`**:
    *   **`AgentService`**, **`TaskService`**: Contain the business logic for interacting with agents and managing tasks, respectively. These are accessed via the dependency injectors.

#### slack/
**Purpose:** Provides a gateway for integrating the Solace AI Connector with the Slack collaboration platform, enabling bot interactions within Slack channels and threads.
**Key Exports:** `SlackGatewayApp`, `SlackGatewayComponent`, and various utility functions.
**Import Examples:**
```python
from gateway.slack.app import SlackGatewayApp
from gateway.slack.component import SlackGatewayComponent
from gateway.slack.utils import generate_a2a_session_id, send_slack_message, correct_slack_markdown
```

#### webhook/
**Purpose:** Provides a universal webhook gateway for receiving HTTP requests from external systems and triggering A2A tasks. It is highly configurable for different authentication methods, payload formats, and target agents.
**Key Exports:** `WebhookGatewayApp`, `WebhookGatewayComponent`
**Import Examples:**
```python
from gateway.webhook.app import WebhookGatewayApp
from gateway.webhook.component import WebhookGatewayComponent
from gateway.webhook.dependencies import get_sac_component
```

## Complete Usage Guide
This guide provides practical examples of how to use the components and frameworks within the `gateway` directory.

### 1. How to Create a Custom Gateway
This example shows how to use the `base` module to build a new gateway for a hypothetical external platform.

```python
# my_gateway/app.py
from gateway.base.app import BaseGatewayApp
from .component import MyGatewayComponent

class MyGatewayApp(BaseGatewayApp):
    """Defines the application and its configuration for My Platform."""
    SPECIFIC_APP_SCHEMA_PARAMS = [
        {
            "name": "my_platform_api_key",
            "required": True,
            "type": "string",
            "

================================================================================

## Section 20: gateway/http_sse/components/components_llm.txt

**Source file:** `gateway/http_sse/components/components_llm.txt`

## Quick Summary
This directory contains components for the HTTP SSE (Server-Sent Events) gateway, designed to work within the Solace AI Connector (SAC) framework. The primary component forwards messages received from the Solace broker to an internal queue, enabling real-time visualization in a web-based user interface.

## Files Overview
- `__init__.py`: Makes the `VisualizationForwarderComponent` class directly importable from the `components` package.
- `visualization_forwarder_component.py`: Defines a component that forwards messages from a broker input to a Python `queue.Queue` for visualization.

## Developer API Reference

### __init__.py
**Purpose:** Exposes the public components of this directory for easy importing.
**Import:** `from gateway.http_sse.components import VisualizationForwarderComponent`

**Exports:**
- `VisualizationForwarderComponent`: The main component class for forwarding messages to a visualization queue.

---

### visualization_forwarder_component.py
**Purpose:** A Solace AI Connector (SAC) component that listens for messages from a `BrokerInput` and forwards them to a specified Python `queue.Queue`. This is primarily used to send data to the Web UI for real-time display.
**Import:** `from gateway.http_sse.components.visualization_forwarder_component import VisualizationForwarderComponent`

**Classes:**
- `VisualizationForwarderComponent(**kwargs: Any)` - A component that forwards messages to a target queue. It is initialized with configuration parameters, most importantly `target_queue_ref`.
  - `invoke(self, message: SolaceMessage, data: Dict[str, Any]) -> None` - The core method called by the SAC framework for each incoming message. It formats the data and places it onto the target queue. This method should not be called directly by developers; the framework handles its execution.

**Constants/Variables:**
- `info: Dict` - A metadata dictionary required by the SAC framework. It describes the component's configuration parameters, input schema, and purpose. This is for framework use and not for direct interaction.

**Usage Examples:**
```python
import queue
from gateway.http_sse.components import VisualizationForwarderComponent
from solace_ai_connector.common.message import Message as SolaceMessage

# 1. Create a target queue that will receive the forwarded messages.
#    This queue is typically managed by another component, like a Web UI backend.
visualization_queue = queue.Queue()

# 2. Instantiate the component, providing a reference to the target queue.
#    This is usually done within a SAC flow configuration file.
forwarder = VisualizationForwarderComponent(
    name="my_forwarder",
    target_queue_ref=visualization_queue
)

# 3. The `invoke` method is called automatically by the SAC framework when a message
#    arrives from a connected BrokerInput component.

# Example of what the consuming component would get from the queue:
# A dictionary containing the message topic, payload, and other details.
#
# if not visualization_queue.empty():
#     forwarded_data = visualization_queue.get()
#     print(f"Received topic: {forwarded_data['topic']}")
#     print(f"Received payload: {forwarded_data['payload']}")
#
# Expected structure of `forwarded_data`:
# {
#     "topic": "some/broker/topic",
#     "payload": {"key": "value"},
#     "user_properties": {"prop1": "value1"},
#     "_original_broker_message": <SolaceMessage object>
# }
```

================================================================================

## Section 21: gateway/http_sse/http_sse_llm.txt

**Source file:** `gateway/http_sse/http_sse_llm.txt`

Here is the comprehensive developer guide for the `http_sse` directory.

## Quick Summary
The `http_sse` directory implements a complete HTTP/SSE (Server-Sent Events) gateway for the A2A (Agent-to-Agent) system. Its primary purpose is to serve a web-based user interface and act as a bridge between standard web protocols (HTTP, WebSockets/SSE) and the backend A2A messaging fabric.

The architecture is centered around the `WebUIBackendComponent`, a custom Solace AI Connector (SAC) component that hosts an embedded FastAPI web server. This component manages shared state and resources, such as the `SSEManager` for real-time updates, the `SessionManager` for user sessions, and the `AgentRegistry` for discovering available agents.

Subdirectories organize the functionality:
-   `routers/` defines the REST API endpoints (e.g., `/tasks`, `/agents`).
-   `services/` contains the business logic that the API endpoints call.
-   `dependencies.py` uses FastAPI's dependency injection system to provide the routers and services with safe access to the shared resources managed by the main component.
-   `components/` contains specialized SAC components, for example, to forward A2A messages for real-time visualization.

This design creates a clean separation of concerns, where the web layer (FastAPI) is decoupled from the core messaging and state management layer (SAC Component).

## Files and Subdirectories Overview
- **Direct files:**
    - `__init__.py`: Standard Python package initializer.
    - `app.py`: Defines the main SAC `WebUIBackendApp`, which specifies configuration and launches the component.
    - `component.py`: The core SAC component that hosts the FastAPI server and manages all shared resources and A2A logic.
    - `dependencies.py`: Provides FastAPI dependency injectors for accessing shared resources like services and managers.
    - `main.py`: The main FastAPI application instance, including middleware, router mounting, and exception handling.
    - `session_manager.py`: Manages web user sessions and maps them to unique A2A client and session IDs.
    - `sse_manager.py`: Manages Server-Sent Event (SSE) connections for streaming real-time updates to clients.
- **Subdirectories:**
    - `components/`: Contains specialized SAC components, such as for forwarding messages to the visualization system.
    - `routers/`: Defines the FastAPI `APIRouter` modules for all REST API endpoints.
    - `services/`: Encapsulates business logic for agents, tasks, and other domain-specific operations.

## Developer API Reference

### Direct Files

#### app.py
**Purpose:** This file defines the `WebUIBackendApp`, a custom SAC (Solace AI Connector) App class. It is responsible for defining the configuration schema for the entire HTTP/SSE gateway and programmatically creating the `WebUIBackendComponent`.
**Import:** `from gateway.http_sse.app import WebUIBackendApp`

**Classes/Functions/Constants:**
-   **`WebUIBackendApp(BaseGatewayApp)`**: The main application class. It extends `BaseGatewayApp` and adds a list of WebUI-specific configuration parameters to the application schema.
-   **`SPECIFIC_APP_SCHEMA_PARAMS: List[Dict[str, Any]]`**: A constant list defining the configuration parameters specific to the HTTP/SSE gateway, such as `session_secret_key`, `fastapi_host`, `fastapi_port`, and various frontend-related settings.

#### component.py
**Purpose:** This is the core component of the gateway. It hosts the FastAPI server, manages all shared state (like the SSE and Session managers), handles the lifecycle of the web server, and implements the logic for translating between external HTTP requests and internal A2A messages.
**Import:** `from gateway.http_sse.component import WebUIBackendComponent`

**Classes/Functions/Constants:**
-   **`WebUIBackendComponent(BaseGatewayComponent)`**: The main component class. Developers will primarily interact with its instances via the dependency injection system.
    -   **Public Accessor Methods (for Dependencies):**
        -   `get_sse_manager() -> SSEManager`: Returns the shared `SSEManager` instance.
        -   `get_session_manager() -> SessionManager`: Returns the shared `SessionManager` instance.
        -   `get_agent_registry() -> AgentRegistry`: Returns the shared `AgentRegistry` instance.
        -   `get_core_a2a_service() -> CoreA2AService`: Returns the core service for creating A2A messages.
        -   `get_shared_artifact_service() -> Optional[BaseArtifactService]`: Returns the service for artifact storage.
        -   `get_namespace() -> str`: Returns the configured A2A namespace.
        -   `get_gateway_id() -> str`: Returns the unique ID of this gateway.
    -   **Core Logic Methods:**
        -   `publish_a2a(topic: str, payload: Dict, user_properties: Optional[Dict] = None)`: Publishes a message onto the A2A messaging fabric. This is the primary method for sending data to agents.
    -   **Gateway-Development-Kit (GDK) Hooks:** These methods implement the `BaseGatewayComponent` abstract interface.
        -   `_start_listener()`: Starts the FastAPI/Uvicorn server.
        -   `_stop_listener()`: Stops the FastAPI/Uvicorn server.
        -   `_translate_external_input(...)`: Translates an incoming HTTP request (e.g., form data with files) into a structured A2A message (`List[A2APart]`).
        -   `_send_update_to_external(...)`: Sends an intermediate status update from an agent back to the client via SSE.
        -

================================================================================

## Section 22: gateway/http_sse/routers/routers_llm.txt

**Source file:** `gateway/http_sse/routers/routers_llm.txt`

Here is the DEVELOPER GUIDE for the `routers` directory.

## Quick Summary
The `routers` directory contains FastAPI `APIRouter` modules that define the REST API endpoints for the HTTP SSE Gateway. Each file groups endpoints by a specific domain of functionality, such as agent discovery, artifact management, user authentication, task submission, and real-time event streaming. These routers are the primary interface for frontend applications and other clients to interact with the gateway.

## Files Overview
- `__init__.py`: Marks the directory as a Python package.
- `agents.py`: API endpoints for discovering available A2A agents.
- `artifacts.py`: REST endpoints for managing session-specific artifacts (upload, download, list, delete).
- `auth.py`: Endpoints for handling the user authentication flow (login, callback, refresh, CSRF).
- `config.py`: API endpoint for providing configuration settings to the frontend application.
- `people.py`: API endpoints for user search functionality, typically for autocomplete features.
- `sessions.py`: API endpoints for managing user sessions (creating new sessions, getting current session info).
- `sse.py`: The Server-Sent Events (SSE) endpoint for streaming real-time task updates to the client.
- `tasks.py`: API endpoints for submitting tasks to agents and managing their lifecycle (e.g., cancellation).
- `users.py`: API endpoint for retrieving information about the currently authenticated user.
- `visualization.py`: API endpoints for managing A2A message visualization streams for monitoring and debugging.

## Developer API Reference

### agents.py
**Purpose:** Provides REST endpoints for agent discovery.
**Import:** `from src.solace_agent_mesh.gateway.http_sse.routers.agents import router`

**Functions:**
- `get_discovered_agents() -> List[AgentCard]`: Retrieves a list of all currently discovered and available A2A agents. The `AgentCard` type contains details about each agent.

**Usage Examples:**
```python
# To include this router in a FastAPI application
from fastapi import FastAPI
from src.solace_agent_mesh.gateway.http_sse.routers.agents import router

app = FastAPI()
app.include_router(router, prefix="/api/v1")

# A client would make a GET request to /api/v1/agents

================================================================================

## Section 23: gateway/http_sse/services/services_llm.txt

**Source file:** `gateway/http_sse/services/services_llm.txt`

Here is the developer guide for the `services` directory.

## Quick Summary
The `services` directory contains the business logic layer for the HTTP SSE Gateway. It encapsulates core functionalities by providing high-level services for agent management, user identity searches, and A2A (Agent-to-Agent) task operations. These services abstract the complexities of interacting with the agent registry, external identity providers, and the underlying A2A messaging protocol.

## Files Overview
- `__init__.py` - Marks the directory as a Python package.
- `agent_service.py` - Service for retrieving information about discovered A2A agents.
- `people_service.py` - Service for searching for users via a configured identity service.
- `task_service.py` - Service for handling the cancellation of tasks with A2A agents.

## Developer API Reference

### __init__.py
**Purpose:** This file marks the `services` directory as a Python package, allowing its modules to be imported.
**Import:** N/A - No public interfaces.

---

### agent_service.py
**Purpose:** Provides high-level methods for accessing information about discovered A2A agents from the shared `AgentRegistry`.
**Import:** `from src.solace_agent_mesh.gateway.http_sse.services.agent_service import AgentService`

**Classes:**
- `AgentService(agent_registry: AgentRegistry)` - A service that provides methods for accessing information about discovered A2A agents.
  - `get_all_agents() -> List[AgentCard]` - Retrieves all currently discovered and registered agent cards from the registry.
  - `get_agent_by_name(agent_name: str) -> Optional[AgentCard]` - Retrieves a specific agent card by its unique name. Returns `None` if the agent is not found.

**Usage Examples:**
```python
from typing import List, Optional
from src.solace_agent_mesh.gateway.http_sse.services.agent_service import AgentService
from src.solace_agent_mesh.common.agent_registry import AgentRegistry
from src.solace_agent_mesh.common.types import AgentCard

# In a real application, AgentRegistry would be a shared instance.
# For this example, we'll create a new one and populate it.
agent_registry = AgentRegistry()
my_agent_card = AgentCard(name="data-analyzer", description="Analyzes data files.")
agent_registry.register_agent(my_agent_card)

# 1. Initialize the service with the agent registry
agent_service = AgentService(agent_registry=agent_registry)

# 2. Get all available agents
all_agents = agent_service.get_all_agents()
print(f"Found {len(all_agents)} agent(s).")
for agent in all_agents:
    print(f"- Agent: {agent.name}, Description: {agent.description}")

# 3. Get a specific agent by name
found_agent = agent_service.get_agent_by_name("data-analyzer")
if found_agent:
    print(f"\nSuccessfully retrieved agent: {found_agent.name}")
else:
    print("\nCould not find agent 'data-analyzer'.")

# 4. Try to get a non-existent agent
missing_agent = agent_service.get_agent_by_name("non-existent-agent")
print(f"Result for 'non-existent-agent': {missing_agent}")
```

---

### people_service.py
**Purpose:** Acts as a layer on top of a configured `IdentityService` to provide user search functionality. If no identity service is configured, it gracefully returns empty results.
**Import:** `from src.solace_agent_mesh.gateway.http_sse.services.people_service import PeopleService`

**Classes:**
- `PeopleService(identity_service: Optional[BaseIdentityService])` - A service for searching and retrieving user information.
  - `search_for_users(query: str, limit: int = 10) -> List[Dict[str, Any]]` - Asynchronously searches for users via the identity service. Returns an empty list if the query is too short, no identity service is configured, or an error occurs.

**Usage Examples:**
```python
import asyncio
from typing import Any, Dict, List, Optional
from src.solace_agent_mesh.gateway.http_sse.services.people_service import PeopleService
from src.solace_agent_mesh.common.services.identity_service import BaseIdentityService

# Define a mock identity service for the example
class MockIdentityService(BaseIdentityService):
    async def search_users(self, query: str, limit: int) -> List[Dict[str, Any]]:
        print(f"MockIdentityService: Searching for '{query}' with limit {limit}")
        all_users = [
            {"id": "jdoe", "name": "John Doe", "email": "j.doe@example.com"},
            {"id": "jsmith", "name": "Jane Smith", "email": "j.smith@example.com"},
        ]
        return [user for user in all_users if query.lower() in user["name"].lower()][:limit]

async def main():
    # 1. Initialize with a configured identity service
    identity_service = MockIdentityService()
    people_service = PeopleService(identity_service=identity_service)

    # 2. Search for users
    users = await people_service.search_for_users("john", limit=5)
    print(f"Found {len(users)} user(s): {users}")

    # 3. Initialize without an identity service
    people_service_no_id = PeopleService(identity_service=None)
    
    # 4. Search will return an empty list
    empty_results = await people_service_no_id.search_for_users("jane")
    print(f"Results with no identity service: {empty_results}")

if __name__ == "__main__":
    asyncio.run(main())
```

---

### task_service.py
**Purpose:** Handles the business logic for cancelling A2A tasks. It uses `CoreA2AService` to construct the cancellation message and a provided publisher function to send it over the messaging fabric.
**Import:** `from src.solace_agent_mesh.gateway.http_sse.services.task_service import TaskService, PublishFunc`

**Classes:**
- `TaskService(core_a2a_service: CoreA2AService, publish_func: PublishFunc, namespace: str, gateway_id: str, sse_manager: SSEManager, task_context_map: Dict[str, Dict], task_context_lock: threading.Lock, app_name: str)` - A service for managing A2A task operations.
  - `cancel_task(agent_name: str, task_id: str, client_id: str, user_id: str = "web_user") -> None` - Asynchronously constructs and publishes an A2A `CancelTaskRequest` message for a specific task.

**Type Aliases:**
- `PublishFunc: Callable[[str, Dict, Optional[Dict]], None]` - A callable that sends a message. It takes a topic, a payload dictionary, and optional user properties.

**Usage Examples:**
```python
import asyncio
import threading
from typing import Callable, Dict, Optional

from src.solace_agent_mesh.gateway.http_sse.services.task_service import TaskService, PublishFunc
from src.solace_agent_mesh.core_a2a.service import CoreA2AService
from src.solace_agent_mesh.gateway.http_sse.sse_manager import SSEManager

# Mock dependencies for the example
class MockCoreA2AService(CoreA2AService):
    def cancel_task(self, agent_name, task_id, client_id, user_id):
        topic = f"a2a/request/{agent_name}/cancelTask"
        payload = {"taskId": task_id}
        user_props = {"clientId": client_id, "userId": user_id}
        return topic, payload, user_props

def my_publish_func(topic: str, payload: Dict, user_properties: Optional[Dict]):
    print("\n--- Publishing Message ---")
    print(f"Topic: {topic}")
    print(f"Payload: {payload}")
    print(f"User Properties: {user_properties}")
    print("------------------------")

async def main():
    # 1. Set up dependencies
    core_a2a_service = MockCoreA2AService()
    sse_manager = SSEManager()
    task_context_map = {}
    task_context_lock = threading.Lock()

    # 2. Initialize TaskService
    task_service = TaskService(
        core_a2a_service=core_a2a_service,
        publish_func=my_publish_func,
        namespace="my-namespace",
        gateway_id="gateway-01",
        sse_manager=sse_manager,
        task_context_map=task_context_map,
        task_context_lock=task_context_lock,
        app_name="my-app"
    )

    # 3. Call the cancel_task method
    print("Requesting task cancellation...")
    await task_service.cancel_task(
        agent_name="report-generator",
        task_id="task-12345",
        client_id="client-abcde",
        user_id="test.user"
    )
    print("Task cancellation request sent.")

if __name__ == "__main__":
    asyncio.run(main())
```

================================================================================

## Section 24: llm.txt

**Source file:** `llm.txt`

Here is the comprehensive developer guide for the `src` directory.

## Quick Summary
The `src` directory serves as the main source code root for the Solace AI Connector, containing four primary subsystems that work together to enable comprehensive AI agent communication and hosting. The `agent` directory provides a complete framework for hosting Google ADK agents with A2A protocol support, the `common` directory offers foundational A2A protocol infrastructure and utilities, the `core_a2a` directory provides a reusable service layer for core A2A operations, and the `gateway` directory implements various gateway patterns for external platform integration. These components work together to create a distributed AI agent ecosystem with real-time communication, task delegation, and multi-platform integration capabilities.

## Files and Subdirectories Overview
- **Direct files:**
  - `__init__.py`: Empty package initialization file.
- **Subdirectories:**
  - `agent/`: Complete ADK agent hosting framework with A2A protocol integration and comprehensive tool library.
  - `common/`: Foundational A2A protocol infrastructure, type systems, and client/server implementations.
  - `core_a2a/`: Reusable service layer for core A2A interactions and agent registry operations.
  - `gateway/`: Gateway framework with HTTP/SSE, Slack, and Webhook implementations for external platform integration.

## Developer API Reference

### Direct Files

#### __init__.py
**Purpose:** Standard Python package initializer. It allows the `src` directory and its subdirectories to be treated as a package.
**Import:** `from src import agent, common, gateway`

**Classes/Functions/Constants:**
This file is empty and has no public interfaces.

### Subdirectory APIs

#### agent/
**Purpose:** Provides a complete framework for hosting Google ADK agents with A2A protocol support and a comprehensive, extensible tool library.
**Key Exports:** `SamAgentApp`, `SamAgentComponent`, `AppLlmAgent`, and a wide array of built-in tools for data analysis, web requests, multimedia processing, and inter-agent communication.
**Import Examples:**
```python
from src.solace_agent_mesh.agent.sac.app import SamAgentApp
from src.solace_agent_mesh.agent.sac.component import SamAgentComponent
from src.solace_agent_mesh.agent.adk.app_llm_agent import AppLlmAgent
from src.solace_agent_mesh.agent.tools.builtin_data_analysis_tools import query_data_with_sql
from src.solace_agent_mesh.agent.tools.peer_agent_tool import PeerAgentTool
from src.solace_agent_mesh.agent.tools.web_tools import web_request
from src.solace_agent_mesh.agent.tools.image_tools import create_image_from_description
```

#### common/
**Purpose:** Provides the foundational infrastructure for Agent-to-Agent (A2A) communication, including the core protocol, data types, message translation, and client/server implementations.
**Key Exports:** A2A protocol functions, Pydantic type definitions (`Message`, `Task`, `AgentCard`), `A2AClient` for interacting with agents, `A2AServer` for building agents, and various utilities.
**Import Examples:**
```python
from src.solace_agent_mesh.common.a2a_protocol import get_agent_request_topic
from src.solace_agent_mesh.common.types import Message, Task, AgentCard, TextPart
from src.solace_agent_mesh.common.client import A2AClient, A2ACardResolver
from src.solace_agent_mesh.common.server import A2AServer, InMemoryTaskManager
from src.solace_agent_mesh.common.agent_registry import AgentRegistry
from src.solace_agent_mesh.common.utils.embeds import resolve_embeds_in_string
```

#### core_a2a/
**Purpose:** Provides a reusable, decoupled service layer for core A2A interactions, handling task submission, cancellation, and agent discovery.
**Key Exports:** `CoreA2AService` for managing A2A protocol logic without being tied to a specific gateway or messaging implementation.
**Import Examples:**
```python
from src.solace_agent_mesh.core_a2a.service import CoreA2AService
```

#### gateway/
**Purpose:** Provides a framework and multiple implementations for building gateways that bridge external platforms (like web UIs, Slack, or webhooks) with the A2A messaging system.
**Key Exports:** `BaseGatewayApp` and `BaseGatewayComponent` for creating custom gateways, and concrete implementations like `WebUIBackendApp`, `SlackGatewayApp`, and `WebhookGatewayApp`.
**Import Examples:**
```python
from src.solace_agent_mesh.gateway.base.app import BaseGatewayApp
from src.solace_agent_mesh.gateway.http_sse.app import WebUIBackendApp
from src.solace_agent_mesh.gateway.slack.app import SlackGatewayApp
from src.solace_agent_mesh.gateway.webhook.app import WebhookGatewayApp
from src.solace_agent_mesh.gateway.base.authorization_service import ConfigurableRbacAuthorizationService
```

## Complete Usage Guide
This guide demonstrates how the different subdirectories within `src` work together to build a complete, distributed AI agent system.

### 1. How to import and use functionality from subdirectories
The following examples show how to import and instantiate components from each major subdirectory.

```python
# 1. Import from the 'agent' directory to create an AI agent
from src.solace_agent_mesh.agent.sac.app import SamAgentApp

# 2. Import from the 'common' and 'core_a2a' directories for protocol infrastructure
from src.solace_agent_mesh.common.agent_registry import AgentRegistry
from src.solace_agent_mesh.common.types import AgentCard, AgentCapabilities, AgentSkill
from src.solace_agent_mesh.core_a2a.service import CoreA2AService

# 3. Import from the 'gateway' directory to create interfaces
from src.solace_agent_mesh.gateway.http_sse.app import WebUIBackendApp
from src.solace_agent_mesh.gateway.slack.app import SlackGatewayApp
from src.solace_agent_mesh.gateway.webhook.app import WebhookGatewayApp

# 4. Import tools from the 'agent/tools' subdirectory
from src.solace_agent_mesh.agent.tools.peer_agent_tool import PeerAgentTool
from src.solace_agent_mesh.agent.tools.builtin_data_analysis_tools import query_data_with_sql
```

### 2. How different parts work together
This section shows a step-by-step process for building a system, illustrating the synergy between the components.

#### Step 1: Create an ADK-powered agent (`agent/`)
First, define and configure an agent. This agent will automatically be equipped with a rich set of tools and A2A communication capabilities.

```python
# File: my_system.py
from src.solace_agent_mesh.agent.sac.app import SamAgentApp

# Configure the agent with all capabilities
agent_config = {
    "name": "data-analyst-agent",
    "app_config": {
        "namespace": "myorg/ai-agents",
        "agent_name": "data_analyst",
        "model": "gemini-1.5-pro",
        "instruction": "You are a data analysis expert with access to SQL, charting, web tools, and peer collaboration.",
        "agent_card": {
            "description": "AI agent for comprehensive data analysis and reporting",
            "capabilities": ["data_analysis", "web_research", "chart_generation", "peer_collaboration"]
        },
        "agent_card_publishing": {"interval_seconds": 30},
        "agent_discovery": {"enabled": True},
        "inter_agent_communication": {"allow_list": ["*"]}
    }
}

# Create the agent app (in a real scenario, this is run by the SAC framework)
agent_app = SamAgentApp(agent_config)
```

#### Step 2: Set Up A2A Protocol Infrastructure (`common/` and `core_a2a/`)
Next, set up the core services that manage agent discovery and task routing. This is often handled by the gateway components but can be used directly.

```python
# File: my_system.py (continued)
from src.solace_agent_mesh.common.agent_registry import AgentRegistry
from src.solace_agent_mesh.common.types import AgentCard, AgentCapabilities, AgentSkill
from src.solace_agent_mesh.core_a2a.service import CoreA2AService

# Initialize a shared agent registry
agent_registry = AgentRegistry()

# Create the core A2A service, which uses the registry
namespace = "myorg/ai-agents"
a2a_service = CoreA2AService(agent_registry, namespace)

# Manually register an agent's capabilities (this is usually done automatically by the agent itself)
data_analyst_card = AgentCard(
    name="data_analyst",
    display_name="Data Analyst",
    description="AI agent for data analysis",
    url=f"a2a://{namespace}/data_analyst",
    version="1.0.0",
    capabilities=AgentCapabilities(streaming=True, pushNotifications=True),
    skills=[AgentSkill(id="sql_analysis", name="SQL Data Analysis")]
)
a2a_service.process_discovery_message(data_analyst_card)
```

#### Step 3: Create Gateway Integrations (`gateway/`)
Create one or more gateways to expose the agent(s) to external platforms.

```python
# File: my_system.py (continued)
from src.solace_agent_mesh.gateway.http_sse.app import WebUIBackendApp
from src.solace_agent_mesh.gateway.slack.app import SlackGatewayApp

# Web UI Gateway for browser-based interactions
webui_config = {
    "name": "web-gateway",
    "app_config": {
        "namespace": "myorg/ai-agents",
        "gateway_id": "web-ui-gateway",
        "session_secret_key": "a-very-secret-key",
        "fastapi_host": "0.0.0.0",
        "fastapi_port": 8080,
        "artifact_service": {"type": "local_file", "base_path": "./artifacts"}
    }
}
webui_app = WebUIBackendApp(webui_config)

# Slack Gateway for team collaboration
slack_config = {
    "name": "slack-gateway",
    "app_config": {
        "namespace": "myorg/ai-agents",
        "gateway_id": "slack-gateway",
        "slack_bot_token": "${SLACK_BOT_TOKEN}",
        "slack_app_token": "${SLACK_APP_TOKEN}",
        "default_agent_name": "data_analyst"
    }
}
slack_app = SlackGatewayApp(slack_config)
```

### 3. Common usage patterns

#### Pattern 1: Inter-Agent Communication
An agent can use the `PeerAgentTool` (from `agent/tools/`) to delegate tasks to other agents, leveraging the `common/` protocol infrastructure.

```python
# This code would run within an agent's tool execution context.
from src.solace_agent_mesh.agent.tools.peer_agent_tool import PeerAgentTool

async def analyze_and_delegate_report(component, tool_context):
    # Assume 'component' is the SamAgentComponent instance hosting the current agent.
    
    # Step 1: Perform local analysis (using another tool)
    # ... analysis_result = await query_data_with_sql(...) ...

    # Step 2: Delegate report generation to a specialist agent
    peer_tool = PeerAgentTool(
        target_agent_name="report_generator",
        host_component=component
    )
    
    report_result = await peer_tool.run_async(
        args={
            "task_description": "Generate a professional PDF report from this analysis",
            "analysis_data": "artifact://analysis_result.json",
            "report_format": "PDF"
        },
        tool_context=tool_context
    )
    
    return report_result
```

================================================================================

