## 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...")