Skip to content

digitalkin ¤

DigitalKin SDK!

This package implements the DigitalKin agentic mesh standards.

Modules:

  • __version__

    Version information.

  • community

    Community integrations for DigitalKin.

  • core

    Core of Digitlakin defining the task management and sub-modules.

  • grpc_servers

    This package contains the gRPC server and client implementations.

  • logger

    This module sets up a logger.

  • mixins

    Mixin definitions.

  • models

    This package contains the models for DigitalKin.

  • modules

    Module package for DigitalKin.

  • services

    This package contains the abstract base class for all services.

  • utils

    General utils folder.

Classes:

  • ArchetypeModule

    ArchetypeModule extends BaseModule to implement specific module types.

  • ModuleContext

    ModuleContext provides a container for strategies and resources used by a module.

  • ModuleStatus

    Possible module's state.

  • ServicesConfig

    Service class describing the available services in a Module.

  • ToolModule

    ToolModule extends BaseModule to implement specific module types.

  • TriggerHandler

    Base class for all input-trigger handlers.

ArchetypeModule ¤

ArchetypeModule(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
)

              flowchart TD
              digitalkin.ArchetypeModule[ArchetypeModule]
              digitalkin.modules._base_module.BaseModule[BaseModule]

                              digitalkin.modules._base_module.BaseModule --> digitalkin.ArchetypeModule
                


              click digitalkin.ArchetypeModule href "" "digitalkin.ArchetypeModule"
              click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
            

ArchetypeModule extends BaseModule to implement specific module types.

Parameters:

  • job_id ¤

    (str) –

    Unique job identifier.

  • mission_id ¤

    (str) –

    Mission identifier.

  • setup_id ¤

    (str) –

    Setup identifier.

  • setup_version_id ¤

    (str) –

    Setup version identifier.

  • request_metadata ¤

    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) from the incoming request.

Methods:

Attributes:

status property ¤

status: ModuleStatus

Get the module status.

Returns:

__init_subclass__ ¤

__init_subclass__(**kwargs: Any) -> None

Ensure each subclass has its own copy of mutable class variables.

cleanup abstractmethod async ¤

cleanup() -> None

Run the module.

create_config_setup_model classmethod ¤

create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT

Create the setup model from the setup data.

Parameters:

  • config_setup_data ¤

    (dict[str, Any]) –

    The setup data to create the model from.

Returns:

  • SetupModelT

    The setup model.

create_input_model classmethod ¤

create_input_model(input_data: dict[str, Any]) -> DataModel

Create the input model from the input data.

Parameters:

  • input_data ¤

    (dict[str, Any]) –

    The input data to create the model from.

Returns:

  • DataModel

    The input model, validated against the extended format that

  • DataModel

    includes SDK utility protocols (healthcheck, etc.).

create_output_model classmethod ¤

create_output_model(output_data: dict[str, Any]) -> OutputModelT

Create the output model from the output data.

Parameters:

  • output_data ¤

    (dict[str, Any]) –

    The output data to create the model from.

Returns:

  • OutputModelT

    The output model.

create_secret_model classmethod ¤

create_secret_model(secret_data: dict[str, Any]) -> SecretModelT

Create the secret model from the secret data.

Parameters:

  • secret_data ¤

    (dict[str, Any]) –

    The secret data to create the model from.

Returns:

  • SecretModelT

    The secret model.

create_setup_model async classmethod ¤

create_setup_model(
    setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT

Create the setup model from the setup data.

Creates a filtered setup model instance based on the provided data. Uses get_clean_model() internally to get the appropriate model class with field filtering applied.

Parameters:

  • setup_data ¤

    (dict[str, Any]) –

    The setup data to create the model from.

  • config_fields ¤

    (bool, default: False ) –

    If True, include only fields with json_schema_extra["config"] == True.

Returns:

  • SetupModelT

    An instance of the setup model with the provided data.

discover classmethod ¤

discover() -> None

Discover and register all TriggerHandler subclasses in the specified package or current directory.

Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.

If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.

Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.

get_config_setup_format async classmethod ¤

get_config_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the config setup format model.

The config setup format is used only to initialize the module with configuration data. It includes fields marked with json_schema_extra={"config": True} and excludes hidden runtime fields.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the config setup format as a JSON string.

Raises:

get_cost_format async classmethod ¤

get_cost_format(*, llm_format: bool) -> str

Get the JSON schema of the cost configuration.

Extracts CostConfig from services_config_params["cost"]["config"] and returns as JSON schema.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the cost configuration as a JSON string.

get_input_format async classmethod ¤

get_input_format(*, llm_format: bool) -> str

Get the JSON schema of the input format model.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the input format as a JSON string.

Raises:

get_module_id classmethod ¤

get_module_id() -> str

Get the module ID from environment variable or metadata.

Returns:

  • str

    The module_id from DIGITALKIN_MODULE_ID env var, or metadata module_id,

  • str

    or "unknown" if neither exists.

get_output_format async classmethod ¤

get_output_format(*, llm_format: bool) -> str

Get the JSON schema of the output format model.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the output format as a JSON string.

Raises:

get_secret_format async classmethod ¤

get_secret_format(*, llm_format: bool) -> str

Get the JSON schema of the secret format model.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the secret format as a JSON string.

Raises:

get_select_input_format async classmethod ¤

get_select_input_format() -> str

Get the JSON schema for trigger selection UI.

Returns:

  • str

    The JSON schema with json_schema and ui_schema keys as a JSON string,

  • str

    or empty object if no select_format is defined.

get_setup_format async classmethod ¤

get_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the setup format model.

The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the setup format as a JSON string.

Raises:

initialize abstractmethod async ¤

initialize(context: ModuleContext, setup_data: SetupModelT) -> None

Initialize the module.

register classmethod ¤

Dynamically register the trigger class.

Parameters:

Returns:

run async ¤

run(input_data: InputModelT, setup_data: SetupModelT) -> None

Run the module by dispatching to the appropriate trigger handler.

Parameters:

  • input_data ¤

    (InputModelT) –

    Input data to process.

  • setup_data ¤

    (SetupModelT) –

    Configuration data for the module.

Raises:

  • ValueError

    If no handler for the protocol is found.

run_config_setup async ¤

run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT

Run config setup the module.

The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.

Returns:

  • SetupModelT

    The updated setup model after running the config setup.

start async ¤

start(
    input_data: InputModelT,
    setup_data: SetupModelT,
    callback: Callable[
        [OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
        Coroutine[Any, Any, None],
    ],
    done_callback: Callable | None = None,
) -> None

Start the module.

start_config_setup async ¤

start_config_setup(
    config_setup_data: SetupModelT,
    callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None

Run config setup lifecycle with tool resolution in parallel.

Parameters:

stop async ¤

stop() -> None

Stop the module. Idempotent — second call is a no-op.

ModuleContext ¤

ModuleContext provides a container for strategies and resources used by a module.

This context object is designed to be passed to module components, providing them with access to shared strategies and resources. Additional attributes may be set dynamically.

Parameters:

Methods:

cleanup async ¤

cleanup() -> None

Close all service strategies and release their resources.

create_openai_style_tools ¤

create_openai_style_tools(setup_id: str) -> list[dict[str, Any]]

Create OpenAI-style function calling schemas for a tool module.

Uses tool cache (fast path) with registry fallback. Returns one schema per ToolDefinition (protocol) in the module. Includes cost information both in the description and as separate metadata.

Parameters:

  • setup_id ¤

    (str) –

    Setup ID to look up (checks cache first, then registry).

Returns:

  • list[dict[str, Any]]

    List of OpenAI-style tool schemas, one per protocol. Empty if not found.

create_tool_functions ¤

create_tool_functions(
    slug: str,
) -> list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]

Create tool functions for all protocols in a tool setup.

Returns an async generator per ToolDefinition that calls the remote tool module via gRPC with the protocol auto-injected.

This method only uses the tool cache (no registry fallback). Use this in sync contexts like init methods.

Parameters:

  • slug ¤

    (str) –

    Setup ID to look up in cache.

Returns:

get_module_schemas_by_id async ¤

get_module_schemas_by_id(
    module_id: str, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas by ID, discovering address/port from registry.

Parameters:

  • module_id ¤

    (str) –

    Module identifier to look up in registry.

  • llm_format ¤

    (bool, default: False ) –

    If True, return LLM-optimized schema format.

Returns:

  • dict[str, dict]

    Dictionary containing schemas: {"input": ..., "output": ..., "setup": ..., "secret": ...}

ModuleStatus ¤


              flowchart TD
              digitalkin.ModuleStatus[ModuleStatus]

              

              click digitalkin.ModuleStatus href "" "digitalkin.ModuleStatus"
            

Possible module's state.

ServicesConfig ¤

ServicesConfig(
    services_config_strategies: dict[str, ServicesStrategy | None] = {},
    services_config_params: dict[str, dict[str, Any | None] | None] = {},
    mode: ServicesMode = LOCAL,
    **kwargs: dict[str, Any],
)

              flowchart TD
              digitalkin.ServicesConfig[ServicesConfig]

              

              click digitalkin.ServicesConfig href "" "digitalkin.ServicesConfig"
            

Service class describing the available services in a Module.

This class manages the strategy implementations for various services, allowing them to be switched between local and remote modes.

Parameters:

  • services_config_strategies ¤

    (dict[str, ServicesStrategy | None], default: {} ) –

    Dictionary mapping service names to strategy implementations

  • services_config_params ¤

    (dict[str, dict[str, Any | None] | None], default: {} ) –

    Dictionary mapping service names to configuration parameters

  • mode ¤

    (ServicesMode, default: LOCAL ) –

    The mode of the services (local or remote)

  • **kwargs ¤

    (dict[str, Any], default: {} ) –

    Additional keyword arguments passed to the parent class constructor

Methods:

Attributes:

agent property ¤

Get the agent service strategy class based on the current mode.

communication property ¤

communication: type[CommunicationStrategy]

Get the communication service strategy class based on the current mode.

cost property ¤

Get the cost service strategy class based on the current mode.

filesystem property ¤

filesystem: type[FilesystemStrategy]

Get the filesystem service strategy class based on the current mode.

identity property ¤

Get the identity service strategy class based on the current mode.

registry property ¤

Get the registry service strategy class based on the current mode.

snapshot property ¤

Get the snapshot service strategy class based on the current mode.

storage property ¤

Get the storage service strategy class based on the current mode.

task_manager property ¤

task_manager: type[TaskManagerStrategy]

Get the task_manager service strategy class based on the current mode.

user_profile property ¤

user_profile: type[UserProfileStrategy]

Get the user_profile service strategy class based on the current mode.

get_strategy_config ¤

get_strategy_config(name: str) -> dict[str, Any]

Get the configuration for a specific strategy.

Parameters:

  • name ¤

    (str) –

    The name of the strategy to retrieve the configuration for

Returns:

  • dict[str, Any]

    The configuration for the specified strategy, or empty dict if not found

init_strategy ¤

Initialize a specific strategy.

Parameters:

  • name ¤

    (str) –

    The name of the strategy to initialize

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The setup ID for the strategy

  • setup_version_id ¤

    (str) –

    The setup version ID for the strategy

Returns:

  • Any

    The initialized strategy instance

Raises:

update_mode ¤

update_mode(mode: ServicesMode) -> None

Update the strategy mode.

Parameters:

valid_strategy_names classmethod ¤

valid_strategy_names() -> set[str]

Get the list of valid strategy names.

Returns:

  • set[str]

    The set of valid strategy names.

ToolModule ¤

ToolModule(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
)

              flowchart TD
              digitalkin.ToolModule[ToolModule]
              digitalkin.modules._base_module.BaseModule[BaseModule]

                              digitalkin.modules._base_module.BaseModule --> digitalkin.ToolModule
                


              click digitalkin.ToolModule href "" "digitalkin.ToolModule"
              click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
            

ToolModule extends BaseModule to implement specific module types.

Parameters:

  • job_id ¤

    (str) –

    Unique job identifier.

  • mission_id ¤

    (str) –

    Mission identifier.

  • setup_id ¤

    (str) –

    Setup identifier.

  • setup_version_id ¤

    (str) –

    Setup version identifier.

  • request_metadata ¤

    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) from the incoming request.

Methods:

Attributes:

status property ¤

status: ModuleStatus

Get the module status.

Returns:

__init_subclass__ ¤

__init_subclass__(**kwargs: Any) -> None

Ensure each subclass has its own copy of mutable class variables.

cleanup abstractmethod async ¤

cleanup() -> None

Run the module.

create_config_setup_model classmethod ¤

create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT

Create the setup model from the setup data.

Parameters:

  • config_setup_data ¤

    (dict[str, Any]) –

    The setup data to create the model from.

Returns:

  • SetupModelT

    The setup model.

create_input_model classmethod ¤

create_input_model(input_data: dict[str, Any]) -> DataModel

Create the input model from the input data.

Parameters:

  • input_data ¤

    (dict[str, Any]) –

    The input data to create the model from.

Returns:

  • DataModel

    The input model, validated against the extended format that

  • DataModel

    includes SDK utility protocols (healthcheck, etc.).

create_output_model classmethod ¤

create_output_model(output_data: dict[str, Any]) -> OutputModelT

Create the output model from the output data.

Parameters:

  • output_data ¤

    (dict[str, Any]) –

    The output data to create the model from.

Returns:

  • OutputModelT

    The output model.

create_secret_model classmethod ¤

create_secret_model(secret_data: dict[str, Any]) -> SecretModelT

Create the secret model from the secret data.

Parameters:

  • secret_data ¤

    (dict[str, Any]) –

    The secret data to create the model from.

Returns:

  • SecretModelT

    The secret model.

create_setup_model async classmethod ¤

create_setup_model(
    setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT

Create the setup model from the setup data.

Creates a filtered setup model instance based on the provided data. Uses get_clean_model() internally to get the appropriate model class with field filtering applied.

Parameters:

  • setup_data ¤

    (dict[str, Any]) –

    The setup data to create the model from.

  • config_fields ¤

    (bool, default: False ) –

    If True, include only fields with json_schema_extra["config"] == True.

Returns:

  • SetupModelT

    An instance of the setup model with the provided data.

discover classmethod ¤

discover() -> None

Discover and register all TriggerHandler subclasses in the specified package or current directory.

Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.

If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.

Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.

get_config_setup_format async classmethod ¤

get_config_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the config setup format model.

The config setup format is used only to initialize the module with configuration data. It includes fields marked with json_schema_extra={"config": True} and excludes hidden runtime fields.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the config setup format as a JSON string.

Raises:

get_cost_format async classmethod ¤

get_cost_format(*, llm_format: bool) -> str

Get the JSON schema of the cost configuration.

Extracts CostConfig from services_config_params["cost"]["config"] and returns as JSON schema.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the cost configuration as a JSON string.

get_input_format async classmethod ¤

get_input_format(*, llm_format: bool) -> str

Get the JSON schema of the input format model.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the input format as a JSON string.

Raises:

get_module_id classmethod ¤

get_module_id() -> str

Get the module ID from environment variable or metadata.

Returns:

  • str

    The module_id from DIGITALKIN_MODULE_ID env var, or metadata module_id,

  • str

    or "unknown" if neither exists.

get_output_format async classmethod ¤

get_output_format(*, llm_format: bool) -> str

Get the JSON schema of the output format model.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the output format as a JSON string.

Raises:

get_secret_format async classmethod ¤

get_secret_format(*, llm_format: bool) -> str

Get the JSON schema of the secret format model.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the secret format as a JSON string.

Raises:

get_select_input_format async classmethod ¤

get_select_input_format() -> str

Get the JSON schema for trigger selection UI.

Returns:

  • str

    The JSON schema with json_schema and ui_schema keys as a JSON string,

  • str

    or empty object if no select_format is defined.

get_setup_format async classmethod ¤

get_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the setup format model.

The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤

    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the setup format as a JSON string.

Raises:

initialize abstractmethod async ¤

initialize(context: ModuleContext, setup_data: SetupModelT) -> None

Initialize the module.

register classmethod ¤

Dynamically register the trigger class.

Parameters:

Returns:

run async ¤

run(input_data: InputModelT, setup_data: SetupModelT) -> None

Run the module by dispatching to the appropriate trigger handler.

Parameters:

  • input_data ¤

    (InputModelT) –

    Input data to process.

  • setup_data ¤

    (SetupModelT) –

    Configuration data for the module.

Raises:

  • ValueError

    If no handler for the protocol is found.

run_config_setup async ¤

run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT

Run config setup the module.

The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.

Returns:

  • SetupModelT

    The updated setup model after running the config setup.

start async ¤

start(
    input_data: InputModelT,
    setup_data: SetupModelT,
    callback: Callable[
        [OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
        Coroutine[Any, Any, None],
    ],
    done_callback: Callable | None = None,
) -> None

Start the module.

start_config_setup async ¤

start_config_setup(
    config_setup_data: SetupModelT,
    callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None

Run config setup lifecycle with tool resolution in parallel.

Parameters:

stop async ¤

stop() -> None

Stop the module. Idempotent — second call is a no-op.

TriggerHandler ¤

TriggerHandler(context: ModuleContext)

              flowchart TD
              digitalkin.TriggerHandler[TriggerHandler]
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.TriggerHandler
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                



              click digitalkin.TriggerHandler href "" "digitalkin.TriggerHandler"
              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Base class for all input-trigger handlers.

Each handler declares
  • protocol_key: the Literal value this handler processes
  • handle(): logic to process the validated payload

Methods:

  • add_cost

    Add a cost entry using the cost strategy.

  • append_files_history

    Append files to file history.

  • clear_fh_mission_cache

    Remove a mission's entries from in-memory caches after flush.

  • flush_file_history

    Flush the current mission's dirty file history to storage.

  • get_cost

    Get cost entries for a specific name.

  • get_costs

    Get filtered cost entries.

  • handle

    Asynchronously processes the input data specific to Handler and streams results via the provided callback.

  • load_file_history

    Load file history for the current session.

  • log_debug

    Log debug message using the callbacks strategy.

  • log_error

    Log error message using the callbacks strategy.

  • log_info

    Log info message using the callbacks strategy.

  • log_warning

    Log warning message using the callbacks strategy.

  • read_storage

    Read data from storage.

  • send_message

    Convert agent event to AG-UI protocol and send via context callbacks.

  • store_storage

    Store data using the storage strategy.

  • update_storage

    Update existing data in storage.

  • upsert_storage

    Insert or update data in storage atomically.

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤

    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤

    (str) –

    Name of the cost configuration to use.

  • quantity ¤

    (float) –

    Quantity of units consumed.

append_files_history async ¤

append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤

clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤

flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤

    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤

get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤

    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤

    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

handle abstractmethod async ¤

handle(
    input_data: InputModelT, setup_data: SetupModelT, context: ModuleContext
) -> None

Asynchronously processes the input data specific to Handler and streams results via the provided callback.

Parameters:

  • input_data ¤

    (InputModelT) –

    The input data to be processed by the handler.

  • setup_data ¤

    (SetupModelT) –

    The setup or configuration data required for processing.

  • context ¤

    (ModuleContext) –

    The context object containing module-specific information and resources.

Returns:

  • Any ( None ) –

    The result of the processing, if applicable.

Note

self.send_message: callback used to stream results. (Callable[[OutputModelT], Coroutine[Any, Any, None]])

The callback must be awaited to ensure results are streamed correctly during processing.

load_file_history async ¤

load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤

log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤

    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤

    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤

log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤

    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤

    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤

log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤

    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤

    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤

log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤

    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤

    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤

    (str) –

    Collection name

  • record_id ¤

    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤

send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤

store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤

    (str) –

    Collection name for the data

  • record_id ¤

    (str | None) –

    Optional record identifier

  • data ¤

    (dict[str, Any]) –

    Data to store

  • data_type ¤

    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤

update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤

    (str) –

    Collection name

  • record_id ¤

    (str) –

    Record identifier

  • data ¤

    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤

upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤

    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤

    (str) –

    Collection name

  • record_id ¤

    (str) –

    Record identifier

  • data ¤

    (dict[str, Any]) –

    Data to store or update

  • data_type ¤

    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

__version__ ¤

Version information.

community ¤

Community integrations for DigitalKin.

This package contains community-contributed integrations with various AI frameworks and tools (Agno, LangChain, etc.).

Modules:

  • agno

    Agno framework integration for DigitalKin.

agno ¤

Agno framework integration for DigitalKin.

Adapters, converters, and HITL helpers for building DigitalKin modules on top of the Agno agent framework. Exports:

  • :class:AgnoStreamAdapter — Agno streaming events → DigitalKin events.
  • :func:agui_tool_to_external_function / :func:make_tools_factory — register AG-UI client-side (frontend) tools as Agno external Functions.
  • :class:AgnoHitlRunner, :class:PausedRunStore, :class:PauseInfo, :class:PausedRunRecord, :data:HITL_STORAGE_CONFIG, :func:emit_awaiting_tool_result — human-in-the-loop (HITL) runner that persists a paused Agno run via the module's :class:~digitalkin.services.storage.StorageStrategy and resumes it when the front replies with a ToolMessage.

Modules:

  • agno_adapter

    Adapter to convert Agno events to DigitalKin framework-agnostic events.

  • agui_tools

    AG-UI frontend tools → Agno external Functions.

  • hitl

    Human-in-the-loop (HITL) runner for Agno agents with AG-UI frontend tools.

Classes:

  • AgnoHitlRunner

    High-level runner for an Agno agent with AG-UI frontend-tool support.

  • AgnoStreamAdapter

    Stateful converter: Agno streaming events -> DigitalKin events.

  • PauseInfo

    Summary of a paused Agno run.

  • PausedRunRecord

    Persistent snapshot of an Agno run paused on external tool execution.

  • PausedRunStore

    Thin wrapper around :class:StorageStrategy for the paused_runs collection.

Functions:

Attributes:

HITL_STORAGE_CONFIG module-attribute ¤

HITL_STORAGE_CONFIG: dict[str, type[BaseModel]] = {
    _PAUSED_RUNS_COLLECTION: PausedRunRecord
}

Drop-in storage config fragment — merge into your module's services_config_params.

Example::

services_config_params = {
    "storage": {
        "config": {**HITL_STORAGE_CONFIG, "my_other_collection": MyModel},
        ...
    },
}

AgnoHitlRunner ¤

AgnoHitlRunner(
    *,
    agent: Agent,
    storage: StorageStrategy | None = None,
    store: PausedRunStore | None = None,
    dependency_key: str = "agui_tools",
)

High-level runner for an Agno agent with AG-UI frontend-tool support.

Wraps a configured :class:~agno.agent.Agent and a :class:PausedRunStore, and exposes three levels of API:

  • :meth:run / :meth:continue_paused_run — low-level: stream one Agno run (fresh or resumed) and return a :class:PauseInfo if it paused on an external tool.
  • :meth:try_resume — inspects an AG-UI input and resumes iff a matching :class:~ag_ui.core.types.ToolMessage is present.
  • :meth:handle_agui_input — all-in-one: detects resume vs fresh message, dispatches, and (optionally) emits the awaiting RunFinished event on pause. Use this one from a trigger.

Parameters:

  • agent ¤
    (Agent) –

    The Agno agent. It must be built with tools=make_tools_factory(base_tools) and cache_callables=False — otherwise the frontend tools injected per-run won't reach the LLM.

  • storage ¤
    (StorageStrategy | None, default: None ) –

    Convenience: if provided and store is not, a :class:PausedRunStore is constructed automatically.

  • store ¤
    (PausedRunStore | None, default: None ) –

    Pre-built paused-run store. Wins over storage.

  • dependency_key ¤
    (str, default: 'agui_tools' ) –

    The Agno dependencies key under which the runner passes the per-run AG-UI tool list. Must match the key used by :func:make_tools_factory. Defaults to "agui_tools".

Raises:

  • ValueError

    If neither storage nor store is provided.

Methods:

continue_paused_run async ¤
continue_paused_run(
    thread_id: str,
    tool_results: dict[str, str],
    *,
    send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
    run_id: str | None = None,
    agui_tools: list[Tool] | None = None,
) -> PauseInfo | None

Resume a previously paused run.

Loads the persisted :class:~agno.run.agent.RunOutput, injects the tool results into the matching :class:~agno.run.requirement.RunRequirement entries, and calls :meth:~agno.agent.Agent.acontinue_run. On normal completion the storage record is removed; on re-pause it is refreshed.

Parameters:

  • thread_id ¤
    (str) –

    AG-UI thread identifier (the storage key).

  • tool_results ¤
    (dict[str, str]) –

    Mapping of tool_call_id → serialized result (typically a JSON string). Every pending tool must be resolved — unresolved requirements will stall the run.

  • send ¤
    (Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –

    Digitalkin-event callback (same contract as :meth:run).

  • run_id ¤
    (str | None, default: None ) –

    AG-UI run identifier for this resume turn. Used to emit a synthetic RUN_STARTED before streaming — Agno emits RunContinued (not RunStarted) on resume.

  • agui_tools ¤
    (list[Tool] | None, default: None ) –

    Frontend tool definitions for the resumed run. The AG-UI client should re-send the same list it provided at the original turn so tool schemas stay registered.

Returns:

  • PauseInfo | None

    None on final completion. A fresh :class:PauseInfo when

  • PauseInfo | None

    the resumed run paused again (cascading frontend tools). If

  • PauseInfo | None

    no paused record exists for thread_id, returns None.

handle_agui_input async ¤
handle_agui_input(
    input_data: Any,
    *,
    send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
    context: ModuleContext | None = None,
    message: str | None = None,
    images: list[Any] | None = None,
) -> PauseInfo | None

One-shot dispatch of an AG-UI RunAgentInput.

Handles the three cases in order:

  1. Resume a paused run if the input carries a matching ToolMessage (see :meth:try_resume).
  2. Drop a stale paused record if the input is a new UserMessage while a tool was pending (HITL abandon).
  3. Fresh run on the last UserMessage in input_data.messages (or on the explicit message argument).

When a run pauses (fresh or resumed) and context is provided, this method also emits the AG-UI RunFinished with status="awaiting_tool_result" via :func:emit_awaiting_tool_result. Pass context=None if you want to emit it yourself.

Parameters:

  • input_data ¤
    (Any) –

    Any object with thread_id, messages, and tools attributes (typically an AgUiStreamInput).

  • send ¤
    (Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –

    Digitalkin-event callback (e.g. wrapping self.send_message(context, event) in a trigger).

  • context ¤
    (ModuleContext | None, default: None ) –

    If provided, the awaiting RunFinished is emitted automatically on pause.

  • message ¤
    (str | None, default: None ) –

    Override the user prompt extraction. Normally left as None — the runner picks the last UserMessage content from input_data.messages.

  • images ¤
    (list[Any] | None, default: None ) –

    Optional multimodal inputs forwarded to Agno.

Returns:

  • PauseInfo | None

    None on normal completion (or when no actionable input

  • PauseInfo | None

    was found). A :class:PauseInfo on pause (already emitted to

  • PauseInfo | None

    the front if context was provided).

run async ¤
run(
    message: str,
    *,
    send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
    thread_id: str,
    agui_tools: list[Tool] | None = None,
    images: list[Any] | None = None,
) -> PauseInfo | None

Stream a fresh Agno run.

Parameters:

  • message ¤
    (str) –

    User prompt to send to the agent.

  • send ¤
    (Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –

    Async callback invoked for each digitalkin event produced by :class:AgnoStreamAdapter. Typically maps through :meth:AgUiMixin.send_message.

  • thread_id ¤
    (str) –

    AG-UI thread identifier (used as the paused-run storage key if the run pauses).

  • agui_tools ¤
    (list[Tool] | None, default: None ) –

    Frontend tools declared by the AG-UI client for this run. Merged with the agent's base tools through the factory; None or empty is equivalent to "no frontend tools this turn".

  • images ¤
    (list[Any] | None, default: None ) –

    Optional multimodal inputs forwarded to Agno.

Returns:

  • PauseInfo | None

    None on normal completion. A :class:PauseInfo if the run

  • PauseInfo | None

    paused on one or more external tool calls — the caller is

  • PauseInfo | None

    responsible for emitting the awaiting RunFinished (use

  • PauseInfo | None

    func:emit_awaiting_tool_result or let

  • PauseInfo | None

    meth:handle_agui_input do it).

try_resume async ¤
try_resume(
    input_data: Any, *, send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]
) -> tuple[bool, PauseInfo | None]

Try to resume a paused run from an AG-UI input.

The input_data only needs to duck-type thread_id, messages, and tools (typically an AgUiStreamInput). This method:

  1. Loads the paused record for input_data.thread_id. Returns (False, None) if there is none.
  2. Looks for ToolMessage entries in input_data.messages whose tool_call_id matches a pending one.
  3. If any match → dispatches :meth:continue_paused_run and returns (True, pause_info_or_none).
  4. If no match but the last message is a fresh UserMessage, drops the stale record (HITL abandon) and returns (False, None).

Returns:

  • bool

    (resumed, pause_info):

  • PauseInfo | None
    • (False, None): no resume, caller should run the fresh-message path.
  • tuple[bool, PauseInfo | None]
    • (True, None): resume ran to normal completion.
  • tuple[bool, PauseInfo | None]
    • (True, PauseInfo): resume paused again (cascading tools).

AgnoStreamAdapter ¤

AgnoStreamAdapter()

Stateful converter: Agno streaming events -> DigitalKin events.

Tracks reasoning and content state so that events arriving on RunEvent.run_content are automatically wrapped in proper lifecycle events (TextMessageStarted/Completed, ReasoningStarted/Completed).

Usage::

adapter = AgnoStreamAdapter()
async for raw_event in agent.arun(..., stream=True, stream_events=True):
    for event in adapter.to_digitalkin_events(raw_event):
        await send(event)
for event in adapter.flush():
    await send(event)

Methods:

  • flush

    Emit closing events for any active sequences at end of stream.

  • to_digitalkin_events

    Convert one Agno event into one or more DigitalKin events.

Attributes:

is_paused property ¤
is_paused: bool

Whether the last stream ended on a run_paused event (external tool HITL).

paused_requirements property ¤
paused_requirements: list[Any]

Agno RunRequirement objects carried by the paused run.

paused_tool_executions property ¤
paused_tool_executions: list[Any]

Agno ToolExecution objects awaiting external execution (HITL).

flush ¤
flush() -> list[BaseAgentRunEvent]

Emit closing events for any active sequences at end of stream.

Returns:

to_digitalkin_events ¤
to_digitalkin_events(agno_event: AgnoRunEvent) -> list[BaseAgentRunEvent]

Convert one Agno event into one or more DigitalKin events.

Parameters:

  • agno_event ¤
    (AgnoRunEvent) –

    Event from Agno's streaming API.

Returns:

Raises:

  • ImportError

    If the optional 'agno' dependency is not installed.

PauseInfo dataclass ¤

PauseInfo(
    thread_id: str,
    run_id: str,
    pending_tool_call_ids: list[str],
    new_messages: list[Message] = list(),
)

Summary of a paused Agno run.

Returned by :meth:AgnoHitlRunner.run and related methods whenever the run paused on one or more external tool calls. Callers typically use it to emit the AG-UI awaiting-tool-result event to the front.

new_messages carries the AG-UI messages generated by Agno during the paused run (user echoes, the assistant message with tool_calls, and any tool results emitted before the pause). It's provided because Agno does not emit stream events from which the front can reconstruct the assistant-with-tool-calls message — in particular, when the LLM goes straight from reasoning to a frontend tool call without emitting any text. Consumers typically push these messages to the front via a :class:~ag_ui.core.events.MessagesSnapshotEvent so the client has an authoritative view of the conversation.

PausedRunRecord ¤


              flowchart TD
              digitalkin.community.agno.PausedRunRecord[PausedRunRecord]

              

              click digitalkin.community.agno.PausedRunRecord href "" "digitalkin.community.agno.PausedRunRecord"
            

Persistent snapshot of an Agno run paused on external tool execution.

Stored in the paused_runs collection keyed by thread_id. The payload field holds RunOutput.to_dict() verbatim so :meth:agno.run.agent.RunOutput.from_dict can round-trip the run on any replica when the front replies with the tool result(s).

PausedRunStore ¤

PausedRunStore(storage: StorageStrategy)

Thin wrapper around :class:StorageStrategy for the paused_runs collection.

Owns serialization of :class:~agno.run.agent.RunOutput and keying by thread_id. Instances are cheap — create one per trigger handler.

Parameters:

  • storage ¤
    (StorageStrategy) –

    The module's storage strategy. The collection paused_runs must be registered with :class:PausedRunRecord — use :data:HITL_STORAGE_CONFIG.

Methods:

  • delete

    Remove the paused run record for a thread.

  • load

    Fetch the paused run record for a thread.

  • save

    Serialize and store a paused RunOutput.

delete async ¤
delete(thread_id: str) -> None

Remove the paused run record for a thread.

load async ¤
load(thread_id: str) -> PausedRunRecord | None

Fetch the paused run record for a thread.

Parameters:

  • thread_id ¤
    (str) –

    AG-UI thread identifier.

Returns:

  • The ( PausedRunRecord | None ) –

    class:PausedRunRecord if one exists, otherwise None.

save async ¤
save(run_output: RunOutput, thread_id: str) -> PauseInfo

Serialize and store a paused RunOutput.

Parameters:

  • run_output ¤
    (RunOutput) –

    The paused Agno run (is_paused=True with populated requirements).

  • thread_id ¤
    (str) –

    AG-UI thread identifier (the record key).

Returns:

  • A ( PauseInfo ) –

    class:PauseInfo describing what was persisted.

agui_tool_to_external_function ¤

agui_tool_to_external_function(tool: Tool) -> Function

Wrap an AG-UI tool definition as an Agno external Function.

The resulting :class:Function carries the AG-UI schema as-is (Agno accepts raw JSON Schema via parameters) and is marked with external_execution=True so Agno emits the tool-call events but skips the entrypoint and pauses the run when the LLM invokes it.

Parameters:

  • tool ¤
    (Tool) –

    An :class:ag_ui.core.types.Tool from RunAgentInput.tools.

Returns:

  • An ( Function ) –

    class:agno.tools.function.Function ready to be plugged into

  • Function

    an Agno agent's tool list.

emit_awaiting_tool_result async ¤

emit_awaiting_tool_result(
    context: ModuleContext,
    *,
    thread_id: str,
    run_id: str,
    pending_tool_call_ids: list[str],
) -> None

Emit an AG-UI RunFinished with status="awaiting_tool_result".

This is the protocol signal telling the front "the run paused on a client-side tool; execute it and reply with a ToolMessage". It goes out via context.callbacks.send_message (bypassing the standard :class:~digitalkin.mixins.agui_mixin.AgUiMixin event mapping, which has no notion of an "awaiting" status).

Parameters:

  • context ¤
    (ModuleContext) –

    Current module context.

  • thread_id ¤
    (str) –

    AG-UI thread identifier.

  • run_id ¤
    (str) –

    Run identifier to echo back in the finished event.

  • pending_tool_call_ids ¤
    (list[str]) –

    The tool_call_id values the front must execute and resolve — echoed in result.pending_tool_call_ids so the front can match them.

emit_messages_snapshot async ¤

emit_messages_snapshot(context: ModuleContext, messages: list[Message]) -> None

Emit an AG-UI MessagesSnapshot event.

Typically called just before :func:emit_awaiting_tool_result on a paused run so the front has an authoritative view of the conversation (including the assistant message carrying the frontend tool_calls, which cannot be reconstructed from the streamed tool-call events alone).

Parameters:

  • context ¤
    (ModuleContext) –

    Current module context.

  • messages ¤
    (list[Message]) –

    List of AG-UI messages, typically produced by :func:_agno_messages_to_agui from RunOutput.messages.

make_tools_factory ¤

make_tools_factory(
    base_tools: list[Any], dependency_key: str = _DEFAULT_DEPENDENCY_KEY
) -> Callable[[RunContext], list[Any]]

Build an Agno tools factory that merges base tools with per-run AG-UI tools.

The returned callable is the value you pass to Agent(tools=...). On every run, Agno resolves the factory with the current :class:~agno.run.base.RunContext (see :func:agno.utils.callables.aresolve_callable_tools). The factory reads run_context.dependencies[dependency_key] — the list of :class:~ag_ui.core.types.Tool you passed via agent.arun(dependencies={dependency_key: [...]}) — converts them to external :class:Function objects, and concatenates them with the base_tools.

Parameters:

  • base_tools ¤
    (list[Any]) –

    Toolkits / Functions always available to the agent (e.g. AsyncDuckDuckGoTools()). Passed through unchanged.

  • dependency_key ¤
    (str, default: _DEFAULT_DEPENDENCY_KEY ) –

    The key in run_context.dependencies under which the caller places the per-run AG-UI tool list. Defaults to "agui_tools".

Returns:

  • Callable[[RunContext], list[Any]]

    A callable suitable for :class:agno.agent.Agent's tools=

  • Callable[[RunContext], list[Any]]

    parameter. Set cache_callables=False on the Agent so this

  • Callable[[RunContext], list[Any]]

    factory is re-invoked on every run.

agno_adapter ¤

Adapter to convert Agno events to DigitalKin framework-agnostic events.

This adapter bridges Agno-specific events to the DigitalKin event model, allowing the core DigitalKin SDK to remain independent of Agno.

The adapter owns ALL state management: tracking reasoning/content lifecycle, generating message_id and reasoning_id on each phase start, and emitting proper start/completed events for text message and reasoning sequences.

Classes:

  • AgnoStreamAdapter

    Stateful converter: Agno streaming events -> DigitalKin events.

AgnoStreamAdapter ¤
AgnoStreamAdapter()

Stateful converter: Agno streaming events -> DigitalKin events.

Tracks reasoning and content state so that events arriving on RunEvent.run_content are automatically wrapped in proper lifecycle events (TextMessageStarted/Completed, ReasoningStarted/Completed).

Usage::

adapter = AgnoStreamAdapter()
async for raw_event in agent.arun(..., stream=True, stream_events=True):
    for event in adapter.to_digitalkin_events(raw_event):
        await send(event)
for event in adapter.flush():
    await send(event)

Methods:

  • flush

    Emit closing events for any active sequences at end of stream.

  • to_digitalkin_events

    Convert one Agno event into one or more DigitalKin events.

Attributes:

is_paused property ¤
is_paused: bool

Whether the last stream ended on a run_paused event (external tool HITL).

paused_requirements property ¤
paused_requirements: list[Any]

Agno RunRequirement objects carried by the paused run.

paused_tool_executions property ¤
paused_tool_executions: list[Any]

Agno ToolExecution objects awaiting external execution (HITL).

flush ¤
flush() -> list[BaseAgentRunEvent]

Emit closing events for any active sequences at end of stream.

Returns:

to_digitalkin_events ¤
to_digitalkin_events(agno_event: AgnoRunEvent) -> list[BaseAgentRunEvent]

Convert one Agno event into one or more DigitalKin events.

Parameters:

  • agno_event ¤ (AgnoRunEvent) –

    Event from Agno's streaming API.

Returns:

Raises:

  • ImportError

    If the optional 'agno' dependency is not installed.

agui_tools ¤

AG-UI frontend tools → Agno external Functions.

The AG-UI protocol lets the client declare its own tools in RunAgentInput.tools. Those tools are meant to be executed on the frontend (a UI widget, a browser-local API call, a user prompt, …) rather than by the agent process. This module provides the glue to expose them to an Agno :class:~agno.agent.Agent as regular :class:~agno.tools.function.Function objects marked with external_execution=True: when the LLM "calls" one, Agno pauses the run (via :class:~agno.run.agent.RunPausedEvent) instead of executing an entrypoint — letting the caller stream the tool-call events to the front and resume later via :meth:~agno.agent.Agent.acontinue_run.

Usage::

from digitalkin.community.agno import make_tools_factory
from agno.agent import Agent

agent = Agent(
    tools=make_tools_factory([AsyncDuckDuckGoTools()]),
    cache_callables=False,           # critical — see make_tools_factory
    ...
)

async for ev in agent.arun(
    message,
    dependencies={"agui_tools": input_data.tools},
    stream=True,
    stream_events=True,
):
    ...
Notes

dependencies is Agno's standard per-run injection bus. We use it as a transport channel to hand the frontend tools to the tools factory on every run — the tools themselves are actually registered through the tools=factory mechanism, not through dependencies. cache_callables=False is required so the factory is re-invoked on each run (otherwise the first resolved tool list is cached forever and subsequent requests would not see new frontend tools).

Functions:

agui_tool_to_external_function ¤
agui_tool_to_external_function(tool: Tool) -> Function

Wrap an AG-UI tool definition as an Agno external Function.

The resulting :class:Function carries the AG-UI schema as-is (Agno accepts raw JSON Schema via parameters) and is marked with external_execution=True so Agno emits the tool-call events but skips the entrypoint and pauses the run when the LLM invokes it.

Parameters:

  • tool ¤
    (Tool) –

    An :class:ag_ui.core.types.Tool from RunAgentInput.tools.

Returns:

  • An ( Function ) –

    class:agno.tools.function.Function ready to be plugged into

  • Function

    an Agno agent's tool list.

make_tools_factory ¤
make_tools_factory(
    base_tools: list[Any], dependency_key: str = _DEFAULT_DEPENDENCY_KEY
) -> Callable[[RunContext], list[Any]]

Build an Agno tools factory that merges base tools with per-run AG-UI tools.

The returned callable is the value you pass to Agent(tools=...). On every run, Agno resolves the factory with the current :class:~agno.run.base.RunContext (see :func:agno.utils.callables.aresolve_callable_tools). The factory reads run_context.dependencies[dependency_key] — the list of :class:~ag_ui.core.types.Tool you passed via agent.arun(dependencies={dependency_key: [...]}) — converts them to external :class:Function objects, and concatenates them with the base_tools.

Parameters:

  • base_tools ¤
    (list[Any]) –

    Toolkits / Functions always available to the agent (e.g. AsyncDuckDuckGoTools()). Passed through unchanged.

  • dependency_key ¤
    (str, default: _DEFAULT_DEPENDENCY_KEY ) –

    The key in run_context.dependencies under which the caller places the per-run AG-UI tool list. Defaults to "agui_tools".

Returns:

  • Callable[[RunContext], list[Any]]

    A callable suitable for :class:agno.agent.Agent's tools=

  • Callable[[RunContext], list[Any]]

    parameter. Set cache_callables=False on the Agent so this

  • Callable[[RunContext], list[Any]]

    factory is re-invoked on every run.

hitl ¤

Human-in-the-loop (HITL) runner for Agno agents with AG-UI frontend tools.

This module provides the high-level glue to build an Agno-powered module that supports AG-UI frontend tools — tools declared by the AG-UI client and executed on the front rather than on the agent process. The flow is:

  1. The front sends RunAgentInput with a tools list.
  2. The LLM calls one of those tools.
  3. Agno emits RunPausedEvent (its HITL signal) and freezes the run.
  4. We persist the paused :class:~agno.run.agent.RunOutput via the module's :class:~digitalkin.services.storage.StorageStrategy, keyed by thread_id.
  5. We emit an AG-UI RunFinished with result={"status": "awaiting_tool_result", "pending_tool_call_ids": [...]} so the front knows to execute the tool and reply.
  6. On the next RunAgentInput carrying a matching ToolMessage, we load the paused run, inject the result into the corresponding :class:~agno.run.requirement.RunRequirement, and resume via :meth:~agno.agent.Agent.acontinue_run.

The design keeps the process stateless (every replica can resume any thread) because all the state lives in the storage service.

Typical usage inside a module trigger::

from digitalkin.community.agno import (
    AgnoHitlRunner,
    HITL_STORAGE_CONFIG,
    make_tools_factory,
)

# In your Module class — register the storage schema
services_config_params = {
    "storage": {
        "config": {
            **HITL_STORAGE_CONFIG,
            "agno_sessions": AgnoSession,
            ...
        },
        ...
    },
    ...
}

# In your agent factory
agent = Agent(
    tools=make_tools_factory([MyBaseToolkit()]),
    cache_callables=False,
    ...
)

# In your trigger handler
runner = AgnoHitlRunner(agent=agent, storage=context.storage)
pause_info = await runner.handle_agui_input(
    input_data=input_data,
    send=send,
    context=context,        # enables auto-emission of awaiting RunFinished
)

handle_agui_input will figure out whether this is a fresh user message, a resume of a paused run, or an abandon (new user message while a tool was pending) and dispatch accordingly.

Classes:

  • AgnoHitlRunner

    High-level runner for an Agno agent with AG-UI frontend-tool support.

  • PauseInfo

    Summary of a paused Agno run.

  • PausedRunRecord

    Persistent snapshot of an Agno run paused on external tool execution.

  • PausedRunStore

    Thin wrapper around :class:StorageStrategy for the paused_runs collection.

Functions:

Attributes:

HITL_STORAGE_CONFIG module-attribute ¤
HITL_STORAGE_CONFIG: dict[str, type[BaseModel]] = {
    _PAUSED_RUNS_COLLECTION: PausedRunRecord
}

Drop-in storage config fragment — merge into your module's services_config_params.

Example::

services_config_params = {
    "storage": {
        "config": {**HITL_STORAGE_CONFIG, "my_other_collection": MyModel},
        ...
    },
}
AgnoHitlRunner ¤
AgnoHitlRunner(
    *,
    agent: Agent,
    storage: StorageStrategy | None = None,
    store: PausedRunStore | None = None,
    dependency_key: str = "agui_tools",
)

High-level runner for an Agno agent with AG-UI frontend-tool support.

Wraps a configured :class:~agno.agent.Agent and a :class:PausedRunStore, and exposes three levels of API:

  • :meth:run / :meth:continue_paused_run — low-level: stream one Agno run (fresh or resumed) and return a :class:PauseInfo if it paused on an external tool.
  • :meth:try_resume — inspects an AG-UI input and resumes iff a matching :class:~ag_ui.core.types.ToolMessage is present.
  • :meth:handle_agui_input — all-in-one: detects resume vs fresh message, dispatches, and (optionally) emits the awaiting RunFinished event on pause. Use this one from a trigger.

Parameters:

  • agent ¤
    (Agent) –

    The Agno agent. It must be built with tools=make_tools_factory(base_tools) and cache_callables=False — otherwise the frontend tools injected per-run won't reach the LLM.

  • storage ¤
    (StorageStrategy | None, default: None ) –

    Convenience: if provided and store is not, a :class:PausedRunStore is constructed automatically.

  • store ¤
    (PausedRunStore | None, default: None ) –

    Pre-built paused-run store. Wins over storage.

  • dependency_key ¤
    (str, default: 'agui_tools' ) –

    The Agno dependencies key under which the runner passes the per-run AG-UI tool list. Must match the key used by :func:make_tools_factory. Defaults to "agui_tools".

Raises:

  • ValueError

    If neither storage nor store is provided.

Methods:

continue_paused_run async ¤
continue_paused_run(
    thread_id: str,
    tool_results: dict[str, str],
    *,
    send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
    run_id: str | None = None,
    agui_tools: list[Tool] | None = None,
) -> PauseInfo | None

Resume a previously paused run.

Loads the persisted :class:~agno.run.agent.RunOutput, injects the tool results into the matching :class:~agno.run.requirement.RunRequirement entries, and calls :meth:~agno.agent.Agent.acontinue_run. On normal completion the storage record is removed; on re-pause it is refreshed.

Parameters:

  • thread_id ¤ (str) –

    AG-UI thread identifier (the storage key).

  • tool_results ¤ (dict[str, str]) –

    Mapping of tool_call_id → serialized result (typically a JSON string). Every pending tool must be resolved — unresolved requirements will stall the run.

  • send ¤ (Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –

    Digitalkin-event callback (same contract as :meth:run).

  • run_id ¤ (str | None, default: None ) –

    AG-UI run identifier for this resume turn. Used to emit a synthetic RUN_STARTED before streaming — Agno emits RunContinued (not RunStarted) on resume.

  • agui_tools ¤ (list[Tool] | None, default: None ) –

    Frontend tool definitions for the resumed run. The AG-UI client should re-send the same list it provided at the original turn so tool schemas stay registered.

Returns:

  • PauseInfo | None

    None on final completion. A fresh :class:PauseInfo when

  • PauseInfo | None

    the resumed run paused again (cascading frontend tools). If

  • PauseInfo | None

    no paused record exists for thread_id, returns None.

handle_agui_input async ¤
handle_agui_input(
    input_data: Any,
    *,
    send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
    context: ModuleContext | None = None,
    message: str | None = None,
    images: list[Any] | None = None,
) -> PauseInfo | None

One-shot dispatch of an AG-UI RunAgentInput.

Handles the three cases in order:

  1. Resume a paused run if the input carries a matching ToolMessage (see :meth:try_resume).
  2. Drop a stale paused record if the input is a new UserMessage while a tool was pending (HITL abandon).
  3. Fresh run on the last UserMessage in input_data.messages (or on the explicit message argument).

When a run pauses (fresh or resumed) and context is provided, this method also emits the AG-UI RunFinished with status="awaiting_tool_result" via :func:emit_awaiting_tool_result. Pass context=None if you want to emit it yourself.

Parameters:

  • input_data ¤ (Any) –

    Any object with thread_id, messages, and tools attributes (typically an AgUiStreamInput).

  • send ¤ (Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –

    Digitalkin-event callback (e.g. wrapping self.send_message(context, event) in a trigger).

  • context ¤ (ModuleContext | None, default: None ) –

    If provided, the awaiting RunFinished is emitted automatically on pause.

  • message ¤ (str | None, default: None ) –

    Override the user prompt extraction. Normally left as None — the runner picks the last UserMessage content from input_data.messages.

  • images ¤ (list[Any] | None, default: None ) –

    Optional multimodal inputs forwarded to Agno.

Returns:

  • PauseInfo | None

    None on normal completion (or when no actionable input

  • PauseInfo | None

    was found). A :class:PauseInfo on pause (already emitted to

  • PauseInfo | None

    the front if context was provided).

run async ¤
run(
    message: str,
    *,
    send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
    thread_id: str,
    agui_tools: list[Tool] | None = None,
    images: list[Any] | None = None,
) -> PauseInfo | None

Stream a fresh Agno run.

Parameters:

  • message ¤ (str) –

    User prompt to send to the agent.

  • send ¤ (Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –

    Async callback invoked for each digitalkin event produced by :class:AgnoStreamAdapter. Typically maps through :meth:AgUiMixin.send_message.

  • thread_id ¤ (str) –

    AG-UI thread identifier (used as the paused-run storage key if the run pauses).

  • agui_tools ¤ (list[Tool] | None, default: None ) –

    Frontend tools declared by the AG-UI client for this run. Merged with the agent's base tools through the factory; None or empty is equivalent to "no frontend tools this turn".

  • images ¤ (list[Any] | None, default: None ) –

    Optional multimodal inputs forwarded to Agno.

Returns:

  • PauseInfo | None

    None on normal completion. A :class:PauseInfo if the run

  • PauseInfo | None

    paused on one or more external tool calls — the caller is

  • PauseInfo | None

    responsible for emitting the awaiting RunFinished (use

  • PauseInfo | None

    func:emit_awaiting_tool_result or let

  • PauseInfo | None

    meth:handle_agui_input do it).

try_resume async ¤
try_resume(
    input_data: Any, *, send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]
) -> tuple[bool, PauseInfo | None]

Try to resume a paused run from an AG-UI input.

The input_data only needs to duck-type thread_id, messages, and tools (typically an AgUiStreamInput). This method:

  1. Loads the paused record for input_data.thread_id. Returns (False, None) if there is none.
  2. Looks for ToolMessage entries in input_data.messages whose tool_call_id matches a pending one.
  3. If any match → dispatches :meth:continue_paused_run and returns (True, pause_info_or_none).
  4. If no match but the last message is a fresh UserMessage, drops the stale record (HITL abandon) and returns (False, None).

Returns:

  • bool

    (resumed, pause_info):

  • PauseInfo | None
    • (False, None): no resume, caller should run the fresh-message path.
  • tuple[bool, PauseInfo | None]
    • (True, None): resume ran to normal completion.
  • tuple[bool, PauseInfo | None]
    • (True, PauseInfo): resume paused again (cascading tools).
PauseInfo dataclass ¤
PauseInfo(
    thread_id: str,
    run_id: str,
    pending_tool_call_ids: list[str],
    new_messages: list[Message] = list(),
)

Summary of a paused Agno run.

Returned by :meth:AgnoHitlRunner.run and related methods whenever the run paused on one or more external tool calls. Callers typically use it to emit the AG-UI awaiting-tool-result event to the front.

new_messages carries the AG-UI messages generated by Agno during the paused run (user echoes, the assistant message with tool_calls, and any tool results emitted before the pause). It's provided because Agno does not emit stream events from which the front can reconstruct the assistant-with-tool-calls message — in particular, when the LLM goes straight from reasoning to a frontend tool call without emitting any text. Consumers typically push these messages to the front via a :class:~ag_ui.core.events.MessagesSnapshotEvent so the client has an authoritative view of the conversation.

PausedRunRecord ¤

              flowchart TD
              digitalkin.community.agno.hitl.PausedRunRecord[PausedRunRecord]

              

              click digitalkin.community.agno.hitl.PausedRunRecord href "" "digitalkin.community.agno.hitl.PausedRunRecord"
            

Persistent snapshot of an Agno run paused on external tool execution.

Stored in the paused_runs collection keyed by thread_id. The payload field holds RunOutput.to_dict() verbatim so :meth:agno.run.agent.RunOutput.from_dict can round-trip the run on any replica when the front replies with the tool result(s).

PausedRunStore ¤
PausedRunStore(storage: StorageStrategy)

Thin wrapper around :class:StorageStrategy for the paused_runs collection.

Owns serialization of :class:~agno.run.agent.RunOutput and keying by thread_id. Instances are cheap — create one per trigger handler.

Parameters:

  • storage ¤
    (StorageStrategy) –

    The module's storage strategy. The collection paused_runs must be registered with :class:PausedRunRecord — use :data:HITL_STORAGE_CONFIG.

Methods:

  • delete

    Remove the paused run record for a thread.

  • load

    Fetch the paused run record for a thread.

  • save

    Serialize and store a paused RunOutput.

delete async ¤
delete(thread_id: str) -> None

Remove the paused run record for a thread.

load async ¤
load(thread_id: str) -> PausedRunRecord | None

Fetch the paused run record for a thread.

Parameters:

  • thread_id ¤ (str) –

    AG-UI thread identifier.

Returns:

  • The ( PausedRunRecord | None ) –

    class:PausedRunRecord if one exists, otherwise None.

save async ¤
save(run_output: RunOutput, thread_id: str) -> PauseInfo

Serialize and store a paused RunOutput.

Parameters:

  • run_output ¤ (RunOutput) –

    The paused Agno run (is_paused=True with populated requirements).

  • thread_id ¤ (str) –

    AG-UI thread identifier (the record key).

Returns:

  • A ( PauseInfo ) –

    class:PauseInfo describing what was persisted.

emit_awaiting_tool_result async ¤
emit_awaiting_tool_result(
    context: ModuleContext,
    *,
    thread_id: str,
    run_id: str,
    pending_tool_call_ids: list[str],
) -> None

Emit an AG-UI RunFinished with status="awaiting_tool_result".

This is the protocol signal telling the front "the run paused on a client-side tool; execute it and reply with a ToolMessage". It goes out via context.callbacks.send_message (bypassing the standard :class:~digitalkin.mixins.agui_mixin.AgUiMixin event mapping, which has no notion of an "awaiting" status).

Parameters:

  • context ¤
    (ModuleContext) –

    Current module context.

  • thread_id ¤
    (str) –

    AG-UI thread identifier.

  • run_id ¤
    (str) –

    Run identifier to echo back in the finished event.

  • pending_tool_call_ids ¤
    (list[str]) –

    The tool_call_id values the front must execute and resolve — echoed in result.pending_tool_call_ids so the front can match them.

emit_messages_snapshot async ¤
emit_messages_snapshot(context: ModuleContext, messages: list[Message]) -> None

Emit an AG-UI MessagesSnapshot event.

Typically called just before :func:emit_awaiting_tool_result on a paused run so the front has an authoritative view of the conversation (including the assistant message carrying the frontend tool_calls, which cannot be reconstructed from the streamed tool-call events alone).

Parameters:

  • context ¤
    (ModuleContext) –

    Current module context.

  • messages ¤
    (list[Message]) –

    List of AG-UI messages, typically produced by :func:_agno_messages_to_agui from RunOutput.messages.

core ¤

Core of Digitlakin defining the task management and sub-modules.

Modules:

  • common

    Common utilities for the core module.

  • job_manager

    Job Manager logic.

  • profiling

    Profiling and monitoring tools for DigitalKin tasks and servers.

  • task_manager

    Base task manager logic.

common ¤

Common utilities for the core module.

Modules:

  • factories

    Common factory functions for reducing code duplication in core module.

Classes:

  • ModuleFactory

    Factory for creating module instances with consistent configuration.

  • QueueFactory

    Factory for creating asyncio queues with consistent configuration.

ModuleFactory ¤

Factory for creating module instances with consistent configuration.

Methods:

create_module_instance staticmethod ¤
create_module_instance(
    module_class: type[BaseModule],
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> BaseModule

Create a module instance with standard parameters.

This factory method centralizes module instantiation to ensure consistent parameter passing across the codebase.

Parameters:

  • module_class ¤
    (type[BaseModule]) –

    The module class to instantiate

  • job_id ¤
    (str) –

    Unique job identifier

  • mission_id ¤
    (str) –

    Mission identifier

  • setup_id ¤
    (str) –

    Setup identifier

  • setup_version_id ¤
    (str) –

    Setup version identifier

  • request_metadata ¤
    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • BaseModule

    Instantiated module

Raises:

Example

module = ModuleFactory.create_module_instance( MyModule, job_id="job_123", mission_id="mission:test", setup_id="setup:config", setup_version_id="v1.0", )

QueueFactory ¤

Factory for creating asyncio queues with consistent configuration.

Methods:

create_bounded_queue staticmethod ¤
create_bounded_queue(maxsize: int = DEFAULT_MAX_QUEUE_SIZE) -> Queue

Create a bounded asyncio queue with standard configuration.

Parameters:

  • maxsize ¤
    (int, default: DEFAULT_MAX_QUEUE_SIZE ) –

    Maximum queue size (default 1000, 0 means unlimited)

Returns:

  • Queue

    Bounded asyncio.Queue instance

Raises:

Example

queue = QueueFactory.create_bounded_queue()

or with custom size¤

queue = QueueFactory.create_bounded_queue(maxsize=500)

unlimited queue¤

queue = QueueFactory.create_bounded_queue(maxsize=0)

factories ¤

Common factory functions for reducing code duplication in core module.

Classes:

  • ModuleFactory

    Factory for creating module instances with consistent configuration.

  • QueueFactory

    Factory for creating asyncio queues with consistent configuration.

ModuleFactory ¤

Factory for creating module instances with consistent configuration.

Methods:

create_module_instance staticmethod ¤
create_module_instance(
    module_class: type[BaseModule],
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> BaseModule

Create a module instance with standard parameters.

This factory method centralizes module instantiation to ensure consistent parameter passing across the codebase.

Parameters:

  • module_class ¤ (type[BaseModule]) –

    The module class to instantiate

  • job_id ¤ (str) –

    Unique job identifier

  • mission_id ¤ (str) –

    Mission identifier

  • setup_id ¤ (str) –

    Setup identifier

  • setup_version_id ¤ (str) –

    Setup version identifier

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • BaseModule

    Instantiated module

Raises:

Example

module = ModuleFactory.create_module_instance( MyModule, job_id="job_123", mission_id="mission:test", setup_id="setup:config", setup_version_id="v1.0", )

QueueFactory ¤

Factory for creating asyncio queues with consistent configuration.

Methods:

create_bounded_queue staticmethod ¤
create_bounded_queue(maxsize: int = DEFAULT_MAX_QUEUE_SIZE) -> Queue

Create a bounded asyncio queue with standard configuration.

Parameters:

  • maxsize ¤ (int, default: DEFAULT_MAX_QUEUE_SIZE ) –

    Maximum queue size (default 1000, 0 means unlimited)

Returns:

  • Queue

    Bounded asyncio.Queue instance

Raises:

Example

queue = QueueFactory.create_bounded_queue()

or with custom size¤

queue = QueueFactory.create_bounded_queue(maxsize=500)

unlimited queue¤

queue = QueueFactory.create_bounded_queue(maxsize=0)

job_manager ¤

Job Manager logic.

Modules:

base_job_manager ¤

Background module manager.

Classes:

  • BaseJobManager

    Abstract base class for managing background module jobs.

BaseJobManager ¤

              flowchart TD
              digitalkin.core.job_manager.base_job_manager.BaseJobManager[BaseJobManager]

              

              click digitalkin.core.job_manager.base_job_manager.BaseJobManager href "" "digitalkin.core.job_manager.base_job_manager.BaseJobManager"
            

Abstract base class for managing background module jobs.

Uses composition to delegate task lifecycle management to a TaskManager.

Parameters:

  • module_class ¤
    (type[BaseModule]) –

    The class of the module to be managed.

  • services_mode ¤
    (ServicesMode) –

    The mode of operation for the services (e.g., ASYNC or SYNC).

  • task_manager ¤
    (BaseTaskManager) –

    The task manager instance to use for task lifecycle management.

Methods:

Attributes:

tasks property ¤
tasks: dict[str, Any]

Get tasks from the task manager.

tasks_sessions property ¤
tasks_sessions: dict[str, TaskSession]

Get task sessions from the task manager.

cancel_task async ¤
cancel_task(task_id: str, mission_id: str, timeout: float | None = None) -> bool

Cancel a task.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

  • timeout ¤ (float | None, default: None ) –

    Optional timeout in seconds to wait for the cancellation to complete.

Returns:

  • bool ( bool ) –

    True if the task was successfully cancelled, False otherwise.

clean_session async ¤
clean_session(task_id: str, mission_id: str) -> bool

Clean a task's session.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

Returns:

  • bool ( bool ) –

    True if the task was successfully cancelled, False otherwise.

create_config_setup_instance_job abstractmethod async ¤
create_config_setup_instance_job(
    config_setup_data: SetupModelT,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> str

Create and start a new module job.

This method initializes a new module job, assigns it a unique job ID, and starts it in the background.

Parameters:

  • config_setup_data ¤ (SetupModelT) –

    The input data required to start the job.

  • mission_id ¤ (str) –

    The mission ID associated with the job.

  • setup_id ¤ (str) –

    The setup ID.

  • setup_version_id ¤ (str) –

    The setup version ID.

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • str ( str ) –

    The unique identifier (job ID) of the created job.

Raises:

  • Exception

    If the module fails to start.

create_module_instance_job abstractmethod async ¤
create_module_instance_job(
    input_data: InputModelT,
    setup_data: SetupModelT,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> str

Create and start a new job for the module's instance.

Parameters:

  • input_data ¤ (InputModelT) –

    The input data required to start the job.

  • setup_data ¤ (SetupModelT) –

    The setup configuration for the module.

  • mission_id ¤ (str) –

    The mission ID associated with the job.

  • setup_id ¤ (str) –

    The setup ID.

  • setup_version_id ¤ (str) –

    The setup version ID associated with the module.

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • str ( str ) –

    The unique identifier (job ID) of the created job.

create_task async ¤
create_task(
    task_id: str,
    mission_id: str,
    module: BaseModule,
    coro: Coroutine[Any, Any, None],
    **kwargs: Any,
) -> None

Create a task using the task manager.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier

  • module ¤ (BaseModule) –

    Module instance

  • coro ¤ (Coroutine[Any, Any, None]) –

    Coroutine to execute

  • **kwargs ¤ (Any, default: {} ) –

    Additional arguments for task creation

generate_config_setup_module_response abstractmethod async ¤
generate_config_setup_module_response(job_id: str) -> SetupModelT | ModuleCodeModel

Generate a stream consumer for a module's output data.

This method creates an asynchronous generator that streams output data from a specific module job. If the module does not exist, it generates an error message.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job.

Returns:

  • SetupModelT | ModuleCodeModel

    SetupModelT | ModuleCodeModel: the SetupModelT object fully processed, or an error code.

generate_stream_consumer abstractmethod ¤
generate_stream_consumer(
    job_id: str,
) -> AbstractAsyncContextManager[AsyncGenerator[dict[str, Any], None]]

Generate a stream consumer for the job's message stream.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job to filter messages for.

Yields:

job_specific_callback async staticmethod ¤
job_specific_callback(
    callback: Callable[[str, DataModel | ModuleCodeModel], Coroutine[Any, Any, None]],
    job_id: str,
) -> Callable[[DataModel | ModuleCodeModel], Coroutine[Any, Any, None]]

Generate a job-specific callback function.

Parameters:

Returns:

list_modules abstractmethod async ¤
list_modules() -> dict[str, dict[str, Any]]

List all modules along with their statuses.

Returns:

  • dict[str, dict[str, Any]]

    dict[str, dict[str, Any]]: A dictionary containing information about all modules and their statuses.

send_signal async ¤

Send signal to a task.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

  • signal_type ¤ (str) –

    Type of signal to send.

  • payload ¤ (dict) –

    Payload data for the signal.

Returns:

  • bool ( bool ) –

    True if the signal was successfully sent, False otherwise.

shutdown async ¤
shutdown(mission_id: str, timeout: float = 30.0) -> None

Shutdown all tasks.

start abstractmethod async ¤
start() -> None

Start the job manager.

This method initializes any necessary resources or configurations required for the job manager to function.

stop async ¤
stop() -> None

Stop the job manager and clean up resources.

Default no-op. Subclasses with external connections override.

stop_all_modules abstractmethod async ¤
stop_all_modules() -> None

Stop all currently running module jobs.

This method ensures that all active jobs are gracefully terminated.

stop_module abstractmethod async ¤
stop_module(job_id: str) -> bool

Stop a running module job.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job to stop.

Returns:

  • bool ( bool ) –

    True if the job was successfully stopped, False if it does not exist.

wait_for_completion abstractmethod async ¤
wait_for_completion(job_id: str) -> None

Wait for a task to complete.

This method blocks until the specified job has reached a terminal state. The implementation varies by job manager type: - SingleJobManager: Awaits the asyncio.Task directly - TaskiqJobManager: Polls task status

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job to wait for.

Raises:

  • KeyError

    If the job_id is not found.

single_job_manager ¤

Background module manager with single instance.

Classes:

SingleJobManager ¤
SingleJobManager(
    module_class: type[BaseModule],
    services_mode: ServicesMode,
    default_timeout: float = 300.0,
    max_concurrent_tasks: int = int(get("DIGITALKIN_MAX_CONCURRENT_TASKS", "100")),
)

              flowchart TD
              digitalkin.core.job_manager.single_job_manager.SingleJobManager[SingleJobManager]
              digitalkin.core.job_manager.base_job_manager.BaseJobManager[BaseJobManager]

                              digitalkin.core.job_manager.base_job_manager.BaseJobManager --> digitalkin.core.job_manager.single_job_manager.SingleJobManager
                


              click digitalkin.core.job_manager.single_job_manager.SingleJobManager href "" "digitalkin.core.job_manager.single_job_manager.SingleJobManager"
              click digitalkin.core.job_manager.base_job_manager.BaseJobManager href "" "digitalkin.core.job_manager.base_job_manager.BaseJobManager"
            

Manages a single instance of a module job.

This class ensures that only one instance of a module job is active at a time. It provides functionality to create, stop, and monitor module jobs, as well as to handle their output data.

Parameters:

  • module_class ¤
    (type[BaseModule]) –

    The class of the module to be managed.

  • services_mode ¤
    (ServicesMode) –

    The mode of operation for the services (e.g., ASYNC or SYNC).

  • default_timeout ¤
    (float, default: 300.0 ) –

    Default timeout for task operations

  • max_concurrent_tasks ¤
    (int, default: int(get('DIGITALKIN_MAX_CONCURRENT_TASKS', '100')) ) –

    Maximum number of concurrent tasks

Methods:

Attributes:

tasks property ¤
tasks: dict[str, Any]

Get tasks from the task manager.

tasks_sessions property ¤
tasks_sessions: dict[str, TaskSession]

Get task sessions from the task manager.

add_to_queue async ¤
add_to_queue(job_id: str, output_data: DataModel | ModuleCodeModel) -> None

Add output data to the queue for a specific job.

Behavior depends on the configured backpressure strategy: - BLOCK: await with timeout, raise TimeoutError if queue stays full. - DROP_OLDEST: wait briefly, then drop oldest message to make room. - REJECT: attempt non-blocking put, discard new message if full.

Rejects writes after stream is closed to prevent message loss.

Parameters:

Raises:

  • TimeoutError

    When using BLOCK strategy and the queue remains full past the timeout.

cancel_task async ¤
cancel_task(task_id: str, mission_id: str, timeout: float | None = None) -> bool

Cancel a task.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

  • timeout ¤ (float | None, default: None ) –

    Optional timeout in seconds to wait for the cancellation to complete.

Returns:

  • bool ( bool ) –

    True if the task was successfully cancelled, False otherwise.

clean_session async ¤
clean_session(task_id: str, mission_id: str) -> bool

Clean a task's session.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

Returns:

  • bool ( bool ) –

    True if the task was successfully cleaned, False otherwise.

create_config_setup_instance_job async ¤
create_config_setup_instance_job(
    config_setup_data: SetupModelT,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> str

Create and start a new module setup configuration job.

Parameters:

  • config_setup_data ¤ (SetupModelT) –

    The input data required to start the job.

  • mission_id ¤ (str) –

    The mission ID associated with the job.

  • setup_id ¤ (str) –

    The setup ID associated with the module.

  • setup_version_id ¤ (str) –

    The setup ID.

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • str ( str ) –

    The unique identifier (job ID) of the created job.

Raises:

  • Exception

    If the module fails to start.

create_module_instance_job async ¤
create_module_instance_job(
    input_data: InputModelT,
    setup_data: SetupModelT,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> str

Create and start a new module job.

Parameters:

  • input_data ¤ (InputModelT) –

    The input data required to start the job.

  • setup_data ¤ (SetupModelT) –

    The setup configuration for the module.

  • mission_id ¤ (str) –

    The mission ID associated with the job.

  • setup_id ¤ (str) –

    The setup ID associated with the module.

  • setup_version_id ¤ (str) –

    The setup Version ID associated with the module.

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • str ( str ) –

    The unique identifier (job ID) of the created job.

Raises:

  • Exception

    If the module fails to start.

create_task async ¤
create_task(
    task_id: str,
    mission_id: str,
    module: BaseModule,
    coro: Coroutine[Any, Any, None],
    **kwargs: Any,
) -> None

Create a task using the task manager.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier

  • module ¤ (BaseModule) –

    Module instance

  • coro ¤ (Coroutine[Any, Any, None]) –

    Coroutine to execute

  • **kwargs ¤ (Any, default: {} ) –

    Additional arguments for task creation

generate_config_setup_module_response async ¤
generate_config_setup_module_response(job_id: str) -> SetupModelT | ModuleCodeModel

Generate a stream consumer for a module's output data.

This method creates an asynchronous generator that streams output data from a specific module job. If the module does not exist, it generates an error message.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job.

Returns:

  • SetupModelT | ModuleCodeModel

    SetupModelT | ModuleCodeModel: the SetupModelT object fully processed.

generate_stream_consumer async ¤
generate_stream_consumer(
    job_id: str,
) -> AsyncIterator[AsyncGenerator[dict[str, Any], None]]

Generate a stream consumer for a module's output data.

This method creates an asynchronous generator that streams output data from a specific module job. If the module does not exist, it generates an error message.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job.

Yields:

job_specific_callback async staticmethod ¤
job_specific_callback(
    callback: Callable[[str, DataModel | ModuleCodeModel], Coroutine[Any, Any, None]],
    job_id: str,
) -> Callable[[DataModel | ModuleCodeModel], Coroutine[Any, Any, None]]

Generate a job-specific callback function.

Parameters:

Returns:

list_modules async ¤
list_modules() -> dict[str, dict[str, Any]]

List all modules along with their statuses.

Returns:

  • dict[str, dict[str, Any]]

    dict[str, dict[str, Any]]: A dictionary containing information about all modules and their statuses.

send_signal async ¤

Send signal to a task.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

  • signal_type ¤ (str) –

    Type of signal to send.

  • payload ¤ (dict) –

    Payload data for the signal.

Returns:

  • bool ( bool ) –

    True if the signal was successfully sent, False otherwise.

shutdown async ¤
shutdown(mission_id: str, timeout: float = 30.0) -> None

Shutdown all tasks.

start async ¤
start() -> None

Start manager (no-op, no external connections needed).

stop async ¤
stop() -> None

Stop the job manager and clean up resources.

Default no-op. Subclasses with external connections override.

stop_all_modules async ¤
stop_all_modules() -> None

Stop all currently running module jobs.

stop_module async ¤
stop_module(job_id: str) -> bool

Stop a running module job.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job to stop.

Returns:

  • bool ( bool ) –

    True if the module was successfully stopped, False if it does not exist.

Raises:

  • Exception

    If an error occurs while stopping the module.

wait_for_completion async ¤
wait_for_completion(job_id: str) -> None

Wait for a task to complete by awaiting its asyncio.Task.

Idempotent — safe to call after the task has already been cleaned up (e.g. by deferred cleanup during signal cancellation).

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job to wait for.

taskiq_broker ¤

Taskiq broker & RSTREAM producer for the job manager.

Classes:

Functions:

  • run_config_module

    TaskIQ task allowing a module to compute in the background asynchronously.

  • run_start_module

    TaskIQ task allowing a module to compute in the background asynchronously.

PickleFormatter ¤

              flowchart TD
              digitalkin.core.job_manager.taskiq_broker.PickleFormatter[PickleFormatter]

              

              click digitalkin.core.job_manager.taskiq_broker.PickleFormatter href "" "digitalkin.core.job_manager.taskiq_broker.PickleFormatter"
            

Formatter that pickles the JSON-dumped TaskiqMessage.

This lets you send arbitrary Python objects (classes, functions, etc.) by first converting to JSON-safe primitives, then pickling that string.

Methods:

  • dumps

    Dumps message from python complex object to JSON.

  • loads

    Recreate Python object from bytes.

dumps ¤
dumps(message: TaskiqMessage) -> BrokerMessage

Dumps message from python complex object to JSON.

Parameters:

  • message ¤ (TaskiqMessage) –

    TaskIQ message

Returns:

  • BrokerMessage

    BrokerMessage with mandatory information for TaskIQ

loads ¤
loads(message: bytes) -> TaskiqMessage

Recreate Python object from bytes.

Non-pickle messages (e.g. raw JSON left in the queue by other producers) are logged and converted to a no-op TaskiqMessage so that Taskiq acknowledges (consumes) them instead of nack-ing and re-delivering in a loop.

Parameters:

  • message ¤ (bytes) –

    Broker message from bytes.

Returns:

  • TaskiqMessage

    message with TaskIQ format

TaskiqBrokerConfig ¤

Configuration and lifecycle management for Taskiq broker and RStream producer.

Methods:

cleanup_global_resources async staticmethod ¤
cleanup_global_resources() -> None

Clean up global resources (producer and broker connections).

This should be called during shutdown to prevent connection leaks.

define_broker staticmethod ¤
define_broker() -> AioPikaBroker

Create AioPikaBroker with tuned QoS for worker prefetch control.

Returns:

  • AioPikaBroker

    Broker connected to RabbitMQ with custom formatter.

define_producer staticmethod ¤
define_producer() -> Producer

Create RStream producer with tuned settings for sustained throughput.

Tuning: - default_batch_publishing_delay: Flush batches every 100ms (default 3s) for lower streaming latency during long-running tasks. - default_context_switch_value: Yield to the event loop every 100 messages (default 1000) to keep concurrent coroutines responsive under heavy output.

Returns:

  • Producer

    Producer connected to RabbitMQ.

init_rstream async staticmethod ¤
init_rstream() -> None

Init a stream for every tasks.

send_message_to_stream async staticmethod ¤
send_message_to_stream(job_id: str, output_data: DataModel | ModuleCodeModel) -> None

Add a message frame to the RStream.

Uses Pydantic's Rust-based model_dump_json() and direct string embedding to avoid the overhead of model_dump() → dict → json.dumps() → encode().

Parameters:

  • job_id ¤ (str) –

    ID of the job that sent the message.

  • output_data ¤ (DataModel | ModuleCodeModel) –

    Message body as a OutputModelT or error / stream_code.

TaskiqLifecycleMiddleware ¤

              flowchart TD
              digitalkin.core.job_manager.taskiq_broker.TaskiqLifecycleMiddleware[TaskiqLifecycleMiddleware]

              

              click digitalkin.core.job_manager.taskiq_broker.TaskiqLifecycleMiddleware href "" "digitalkin.core.job_manager.taskiq_broker.TaskiqLifecycleMiddleware"
            

Lifecycle middleware for structured logging and safety-net EndOfStreamOutput.

Methods:

on_error async ¤
on_error(
    message: TaskiqMessage, result: TaskiqResult, exception: BaseException
) -> None

Safety net: send EndOfStreamOutput if worker task failed to.

post_execute async ¤
post_execute(message: TaskiqMessage, result: TaskiqResult) -> None

Log task completion.

pre_execute async ¤
pre_execute(message: TaskiqMessage) -> TaskiqMessage

Log task start.

Returns:

  • TaskiqMessage

    The unmodified message.

run_config_module async ¤
run_config_module(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    module_class: type[BaseModule],
    services_mode: ServicesMode,
    config_setup_data: dict,
    request_metadata: dict[str, str] | None = None,
    registry_config: dict[str, Any] | None = None,
    context: Context = TaskiqDepends(),
) -> None

TaskIQ task allowing a module to compute in the background asynchronously.

Parameters:

  • mission_id ¤
    (str) –

    str,

  • setup_id ¤
    (str) –

    The setup ID associated with the module.

  • setup_version_id ¤
    (str) –

    The setup ID associated with the module.

  • module_class ¤
    (type[BaseModule]) –

    type[BaseModule],

  • services_mode ¤
    (ServicesMode) –

    ServicesMode,

  • config_setup_data ¤
    (dict) –

    dict,

  • request_metadata ¤
    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

  • registry_config ¤
    (dict[str, Any] | None, default: None ) –

    Registry config (client_config) forwarded from the main process.

  • context ¤
    (Context, default: TaskiqDepends() ) –

    Allow TaskIQ context access

run_start_module async ¤
run_start_module(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    module_class: type[BaseModule],
    services_mode: ServicesMode,
    input_data: dict,
    setup_data: dict,
    request_metadata: dict[str, str] | None = None,
    registry_config: dict[str, Any] | None = None,
    context: Context = TaskiqDepends(),
) -> None

TaskIQ task allowing a module to compute in the background asynchronously.

Parameters:

  • mission_id ¤
    (str) –

    str,

  • setup_id ¤
    (str) –

    The setup ID associated with the module.

  • setup_version_id ¤
    (str) –

    The setup ID associated with the module.

  • module_class ¤
    (type[BaseModule]) –

    type[BaseModule],

  • services_mode ¤
    (ServicesMode) –

    ServicesMode,

  • input_data ¤
    (dict) –

    dict,

  • setup_data ¤
    (dict) –

    dict,

  • request_metadata ¤
    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

  • registry_config ¤
    (dict[str, Any] | None, default: None ) –

    Registry config (client_config) forwarded from the main process.

  • context ¤
    (Context, default: TaskiqDepends() ) –

    Allow TaskIQ context access

taskiq_job_manager ¤

Taskiq job manager module.

Classes:

TaskiqJobManager ¤
TaskiqJobManager(
    module_class: type[BaseModule],
    services_mode: ServicesMode,
    default_timeout: float = 300.0,
    stream_timeout: float = float(get("DIGITALKIN_RSTREAM_TIMEOUT", "30.0")),
)

              flowchart TD
              digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager[TaskiqJobManager]
              digitalkin.core.job_manager.base_job_manager.BaseJobManager[BaseJobManager]

                              digitalkin.core.job_manager.base_job_manager.BaseJobManager --> digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager
                


              click digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager href "" "digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager"
              click digitalkin.core.job_manager.base_job_manager.BaseJobManager href "" "digitalkin.core.job_manager.base_job_manager.BaseJobManager"
            

Taskiq job manager for running modules in Taskiq tasks.

Parameters:

  • module_class ¤
    (type[BaseModule]) –

    The class of the module to be managed

  • services_mode ¤
    (ServicesMode) –

    The mode of operation for the services

  • default_timeout ¤
    (float, default: 300.0 ) –

    Default timeout for task operations

  • stream_timeout ¤
    (float, default: float(get('DIGITALKIN_RSTREAM_TIMEOUT', '30.0')) ) –

    Timeout for stream consumer operations

Methods:

Attributes:

tasks property ¤
tasks: dict[str, Any]

Get tasks from the task manager.

tasks_sessions property ¤
tasks_sessions: dict[str, TaskSession]

Get task sessions from the task manager.

cancel_task async ¤
cancel_task(task_id: str, mission_id: str, timeout: float | None = None) -> bool

Cancel a task.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

  • timeout ¤ (float | None, default: None ) –

    Optional timeout in seconds to wait for the cancellation to complete.

Returns:

  • bool ( bool ) –

    True if the task was successfully cancelled, False otherwise.

clean_session async ¤
clean_session(task_id: str, mission_id: str) -> bool

Clean a task's session.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

Returns:

  • bool ( bool ) –

    True if the task was successfully cancelled, False otherwise.

create_config_setup_instance_job async ¤
create_config_setup_instance_job(
    config_setup_data: SetupModelT,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> str

Create and start a new module setup configuration job.

Parameters:

  • config_setup_data ¤ (SetupModelT) –

    The input data required to start the job.

  • mission_id ¤ (str) –

    The mission ID associated with the job.

  • setup_id ¤ (str) –

    The setup ID associated with the module.

  • setup_version_id ¤ (str) –

    The setup ID.

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • str ( str ) –

    The unique identifier (job ID) of the created job.

Raises:

  • TypeError

    If the function is called with bad data type.

  • ValueError

    If the module fails to start.

create_module_instance_job async ¤
create_module_instance_job(
    input_data: InputModelT,
    setup_data: SetupModelT,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
) -> str

Launches the module_task in Taskiq, returns the Taskiq task id as job_id.

Parameters:

  • input_data ¤ (InputModelT) –

    Input data for the module

  • setup_data ¤ (SetupModelT) –

    Setup data for the module

  • mission_id ¤ (str) –

    Mission ID for the module

  • setup_id ¤ (str) –

    The setup ID associated with the module.

  • setup_version_id ¤ (str) –

    The setup ID associated with the module.

  • request_metadata ¤ (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) to forward to the module.

Returns:

  • job_id ( str ) –

    The Taskiq task id.

Raises:

create_task async ¤
create_task(
    task_id: str,
    mission_id: str,
    module: BaseModule,
    coro: Coroutine[Any, Any, None],
    **kwargs: Any,
) -> None

Create a task using the task manager.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier

  • module ¤ (BaseModule) –

    Module instance

  • coro ¤ (Coroutine[Any, Any, None]) –

    Coroutine to execute

  • **kwargs ¤ (Any, default: {} ) –

    Additional arguments for task creation

generate_config_setup_module_response async ¤
generate_config_setup_module_response(job_id: str) -> SetupModelT

Generate a stream consumer for a module's output data.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job.

Returns:

  • SetupModelT ( SetupModelT ) –

    the SetupModelT object fully processed.

Raises:

  • TimeoutError

    If waiting for the setup response times out.

generate_stream_consumer async ¤
generate_stream_consumer(
    job_id: str,
) -> AsyncIterator[AsyncGenerator[dict[str, Any], None]]

Generate a stream consumer for the RStream stream.

Parameters:

  • job_id ¤ (str) –

    The job ID to filter messages.

Yields:

get_module_status async ¤
get_module_status(job_id: str) -> str

Get module status from local session.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job.

Returns:

  • str

    Status string (e.g. "pending", "running", "completed", "failed", "cancelled").

job_specific_callback async staticmethod ¤
job_specific_callback(
    callback: Callable[[str, DataModel | ModuleCodeModel], Coroutine[Any, Any, None]],
    job_id: str,
) -> Callable[[DataModel | ModuleCodeModel], Coroutine[Any, Any, None]]

Generate a job-specific callback function.

Parameters:

Returns:

list_modules async ¤
list_modules() -> dict[str, dict[str, Any]]

List all modules tracked in the registry with their statuses.

Returns:

  • dict[str, dict[str, Any]]

    dict[str, dict[str, Any]]: A dictionary containing information about all tracked modules.

send_signal async ¤

Send signal to a task.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task.

  • mission_id ¤ (str) –

    Mission identifier.

  • signal_type ¤ (str) –

    Type of signal to send.

  • payload ¤ (dict) –

    Payload data for the signal.

Returns:

  • bool ( bool ) –

    True if the signal was successfully sent, False otherwise.

shutdown async ¤
shutdown(mission_id: str, timeout: float = 30.0) -> None

Shutdown all tasks.

start async ¤
start() -> None

Start the TaskiqJobManager (no-op for external connections).

stop async ¤
stop() -> None

Stop the TaskiqJobManager, cancel workers, and clean up all resources.

stop_all_modules async ¤
stop_all_modules() -> None

Stop all running modules tracked in the registry.

stop_module async ¤
stop_module(job_id: str) -> bool

Stop a running module using TaskManager.

Parameters:

  • job_id ¤ (str) –

    The Taskiq task id to stop.

Returns:

  • bool ( bool ) –

    True if the signal was successfully sent, False otherwise.

wait_for_completion async ¤
wait_for_completion(job_id: str, max_wait: float = 600.0) -> None

Wait for a task to complete via stream-closed event.

Relies on _on_message setting _stream_closed when end_of_stream arrives from RStream. Falls back to max_wait timeout for crash scenarios.

Parameters:

  • job_id ¤ (str) –

    The unique identifier of the job to wait for.

  • max_wait ¤ (float, default: 600.0 ) –

    Maximum time in seconds to wait before giving up.

Raises:

profiling ¤

Profiling and monitoring tools for DigitalKin tasks and servers.

Modules:

  • asyncio_monitor

    Server-level asyncio task monitor via asyncio-inspector.

  • task_profiler

    Per-task profiling wrapper for VizTracer, Yappi, and Pyinstrument.

Classes:

  • AsyncioMonitor

    Server-level asyncio task monitor with HTTP stats endpoint.

  • ProfilerMode

    Profiler backend selection.

  • TaskProfiler

    Per-task profiling wrapper. Zero-cost when mode is NONE.

AsyncioMonitor ¤

AsyncioMonitor(port: int)

Server-level asyncio task monitor with HTTP stats endpoint.

Wraps asyncio-inspector to expose real-time asyncio task statistics on an HTTP endpoint. Gracefully degrades if the package is not installed.

Parameters:

  • port ¤
    (int) –

    HTTP port for the stats endpoint.

Methods:

  • start

    Start the asyncio-inspector HTTP server.

  • stop

    Stop the asyncio-inspector HTTP server.

start async ¤
start() -> None

Start the asyncio-inspector HTTP server.

stop async ¤
stop() -> None

Stop the asyncio-inspector HTTP server.

ProfilerMode ¤


              flowchart TD
              digitalkin.core.profiling.ProfilerMode[ProfilerMode]

              

              click digitalkin.core.profiling.ProfilerMode href "" "digitalkin.core.profiling.ProfilerMode"
            

Profiler backend selection.

TaskProfiler ¤

Per-task profiling wrapper. Zero-cost when mode is NONE.

Wraps VizTracer, Yappi, or Pyinstrument around a task's lifecycle. All exceptions are caught internally — profiler failure never crashes a task.

Yappi profiles the entire process, not individual tasks. When multiple tasks run concurrently, yappi stats reflect all of them.

Parameters:

  • task_id ¤
    (str) –

    Unique identifier for the task being profiled.

  • mode ¤
    (ProfilerMode) –

    Which profiler backend to use.

  • output_dir ¤
    (str) –

    Directory to write profiling output files.

Methods:

  • start

    Start the profiler. No-op when mode is NONE.

  • stop

    Stop the profiler, log summary, and save output. No-op when mode is NONE.

start ¤
start() -> None

Start the profiler. No-op when mode is NONE.

stop ¤
stop() -> None

Stop the profiler, log summary, and save output. No-op when mode is NONE.

asyncio_monitor ¤

Server-level asyncio task monitor via asyncio-inspector.

Classes:

  • AsyncioMonitor

    Server-level asyncio task monitor with HTTP stats endpoint.

AsyncioMonitor ¤
AsyncioMonitor(port: int)

Server-level asyncio task monitor with HTTP stats endpoint.

Wraps asyncio-inspector to expose real-time asyncio task statistics on an HTTP endpoint. Gracefully degrades if the package is not installed.

Parameters:

  • port ¤
    (int) –

    HTTP port for the stats endpoint.

Methods:

  • start

    Start the asyncio-inspector HTTP server.

  • stop

    Stop the asyncio-inspector HTTP server.

start async ¤
start() -> None

Start the asyncio-inspector HTTP server.

stop async ¤
stop() -> None

Stop the asyncio-inspector HTTP server.

task_profiler ¤

Per-task profiling wrapper for VizTracer, Yappi, and Pyinstrument.

Classes:

  • ProfilerMode

    Profiler backend selection.

  • TaskProfiler

    Per-task profiling wrapper. Zero-cost when mode is NONE.

ProfilerMode ¤

              flowchart TD
              digitalkin.core.profiling.task_profiler.ProfilerMode[ProfilerMode]

              

              click digitalkin.core.profiling.task_profiler.ProfilerMode href "" "digitalkin.core.profiling.task_profiler.ProfilerMode"
            

Profiler backend selection.

TaskProfiler ¤

Per-task profiling wrapper. Zero-cost when mode is NONE.

Wraps VizTracer, Yappi, or Pyinstrument around a task's lifecycle. All exceptions are caught internally — profiler failure never crashes a task.

Yappi profiles the entire process, not individual tasks. When multiple tasks run concurrently, yappi stats reflect all of them.

Parameters:

  • task_id ¤
    (str) –

    Unique identifier for the task being profiled.

  • mode ¤
    (ProfilerMode) –

    Which profiler backend to use.

  • output_dir ¤
    (str) –

    Directory to write profiling output files.

Methods:

  • start

    Start the profiler. No-op when mode is NONE.

  • stop

    Stop the profiler, log summary, and save output. No-op when mode is NONE.

start ¤
start() -> None

Start the profiler. No-op when mode is NONE.

stop ¤
stop() -> None

Stop the profiler, log summary, and save output. No-op when mode is NONE.

task_manager ¤

Base task manager logic.

Modules:

base_task_manager ¤

Base task manager with common lifecycle management.

Classes:

BaseTaskManager ¤
BaseTaskManager(default_timeout: float = 300.0)

              flowchart TD
              digitalkin.core.task_manager.base_task_manager.BaseTaskManager[BaseTaskManager]

              

              click digitalkin.core.task_manager.base_task_manager.BaseTaskManager href "" "digitalkin.core.task_manager.base_task_manager.BaseTaskManager"
            

Base task manager with common lifecycle management.

Provides shared functionality for task orchestration, monitoring, signaling, and cancellation. Subclasses implement specific execution strategies (local or remote).

Parameters:

  • default_timeout ¤
    (float, default: 300.0 ) –

    Default timeout for task operations in seconds

Methods:

  • __aenter__

    Enter async context manager.

  • __aexit__

    Exit async context manager and clean up resources.

  • cancel_all_tasks

    Cancel all running tasks.

  • cancel_task

    Cancel a task with graceful shutdown and fallback.

  • clean_session

    Force cleanup of task session, cancelling the task if still running.

  • create_task

    Create and manage a new task.

  • send_signal

    Send signal to a specific task.

  • shutdown

    Graceful shutdown of all tasks.

Attributes:

max_concurrent_tasks property writable ¤
max_concurrent_tasks: int

Maximum number of concurrent tasks.

running_tasks property ¤
running_tasks: set[str]

Get IDs of currently running tasks.

task_count property ¤
task_count: int

Number of active tasks (pending or running).

__aenter__ async ¤
__aenter__() -> Self

Enter async context manager.

Returns:

  • Self

    Self for use in async with statements

__aexit__ async ¤
__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit async context manager and clean up resources.

Parameters:

  • exc_type ¤ (type[BaseException] | None) –

    Exception type if an exception occurred

  • exc_val ¤ (BaseException | None) –

    Exception value if an exception occurred

  • exc_tb ¤ (TracebackType | None) –

    Exception traceback if an exception occurred

cancel_all_tasks async ¤
cancel_all_tasks(
    mission_id: str, timeout: float | None = None
) -> dict[str, bool | BaseException]

Cancel all running tasks.

Parameters:

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float | None, default: None ) –

    Optional timeout for cancellation

Returns:

cancel_task async ¤
cancel_task(task_id: str, mission_id: str, timeout: float | None = None) -> bool

Cancel a task with graceful shutdown and fallback.

Parameters:

  • task_id ¤ (str) –

    The ID of the task to cancel

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float | None, default: None ) –

    Optional timeout for cancellation

Returns:

  • bool

    True if the task was cancelled successfully, False otherwise

clean_session async ¤
clean_session(task_id: str, mission_id: str) -> bool

Force cleanup of task session, cancelling the task if still running.

Parameters:

  • task_id ¤ (str) –

    The ID of the task

  • mission_id ¤ (str) –

    The ID of the mission

Returns:

  • bool

    True if the task session was cleaned successfully, False otherwise.

create_task abstractmethod async ¤
create_task(
    task_id: str, mission_id: str, module: BaseModule, coro: Coroutine[Any, Any, None]
) -> None

Create and manage a new task.

Subclasses implement specific execution strategies.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier

  • module ¤ (BaseModule) –

    Module instance to execute

  • coro ¤ (Coroutine[Any, Any, None]) –

    Coroutine to execute

Raises:

send_signal async ¤

Send signal to a specific task.

Parameters:

  • task_id ¤ (str) –

    The ID of the task

  • mission_id ¤ (str) –

    The ID of the mission

  • signal_type ¤ (str) –

    Type of signal to send

  • payload ¤ (dict) –

    Signal payload

Returns:

  • bool

    True if the signal was sent successfully, False otherwise

shutdown async ¤
shutdown(mission_id: str, timeout: float = 30.0) -> None

Graceful shutdown of all tasks.

Parameters:

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float, default: 30.0 ) –

    Timeout for shutdown operations

local_task_manager ¤

Local task manager for single-process execution.

Classes:

LocalTaskManager ¤
LocalTaskManager(default_timeout: float = 10.0)

              flowchart TD
              digitalkin.core.task_manager.local_task_manager.LocalTaskManager[LocalTaskManager]
              digitalkin.core.task_manager.base_task_manager.BaseTaskManager[BaseTaskManager]

                              digitalkin.core.task_manager.base_task_manager.BaseTaskManager --> digitalkin.core.task_manager.local_task_manager.LocalTaskManager
                


              click digitalkin.core.task_manager.local_task_manager.LocalTaskManager href "" "digitalkin.core.task_manager.local_task_manager.LocalTaskManager"
              click digitalkin.core.task_manager.base_task_manager.BaseTaskManager href "" "digitalkin.core.task_manager.base_task_manager.BaseTaskManager"
            

Task manager for local execution in the same process.

Executes tasks locally using TaskExecutor with the supervisor pattern. Suitable for single-server deployments and development.

Parameters:

  • default_timeout ¤
    (float, default: 10.0 ) –

    Default timeout for task operations in seconds

Methods:

  • __aenter__

    Enter async context manager.

  • __aexit__

    Exit async context manager and clean up resources.

  • cancel_all_tasks

    Cancel all running tasks.

  • cancel_task

    Cancel a task with graceful shutdown and fallback.

  • clean_session

    Force cleanup of task session, cancelling the task if still running.

  • create_task

    Create and execute a task locally using TaskExecutor.

  • send_signal

    Send signal to a specific task.

  • shutdown

    Graceful shutdown of all tasks.

Attributes:

max_concurrent_tasks property writable ¤
max_concurrent_tasks: int

Maximum number of concurrent tasks.

running_tasks property ¤
running_tasks: set[str]

Get IDs of currently running tasks.

task_count property ¤
task_count: int

Number of active tasks (pending or running).

__aenter__ async ¤
__aenter__() -> Self

Enter async context manager.

Returns:

  • Self

    Self for use in async with statements

__aexit__ async ¤
__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit async context manager and clean up resources.

Parameters:

  • exc_type ¤ (type[BaseException] | None) –

    Exception type if an exception occurred

  • exc_val ¤ (BaseException | None) –

    Exception value if an exception occurred

  • exc_tb ¤ (TracebackType | None) –

    Exception traceback if an exception occurred

cancel_all_tasks async ¤
cancel_all_tasks(
    mission_id: str, timeout: float | None = None
) -> dict[str, bool | BaseException]

Cancel all running tasks.

Parameters:

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float | None, default: None ) –

    Optional timeout for cancellation

Returns:

cancel_task async ¤
cancel_task(task_id: str, mission_id: str, timeout: float | None = None) -> bool

Cancel a task with graceful shutdown and fallback.

Parameters:

  • task_id ¤ (str) –

    The ID of the task to cancel

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float | None, default: None ) –

    Optional timeout for cancellation

Returns:

  • bool

    True if the task was cancelled successfully, False otherwise

clean_session async ¤
clean_session(task_id: str, mission_id: str) -> bool

Force cleanup of task session, cancelling the task if still running.

Parameters:

  • task_id ¤ (str) –

    The ID of the task

  • mission_id ¤ (str) –

    The ID of the mission

Returns:

  • bool

    True if the task session was cleaned successfully, False otherwise.

create_task async ¤
create_task(
    task_id: str, mission_id: str, module: BaseModule, coro: Coroutine[Any, Any, None]
) -> None

Create and execute a task locally using TaskExecutor.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier

  • module ¤ (BaseModule) –

    Module instance to execute

  • coro ¤ (Coroutine[Any, Any, None]) –

    Coroutine to execute

Raises:

send_signal async ¤

Send signal to a specific task.

Parameters:

  • task_id ¤ (str) –

    The ID of the task

  • mission_id ¤ (str) –

    The ID of the mission

  • signal_type ¤ (str) –

    Type of signal to send

  • payload ¤ (dict) –

    Signal payload

Returns:

  • bool

    True if the signal was sent successfully, False otherwise

shutdown async ¤
shutdown(mission_id: str, timeout: float = 30.0) -> None

Graceful shutdown of all tasks.

Parameters:

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float, default: 30.0 ) –

    Timeout for shutdown operations

remote_task_manager ¤

Remote task manager for distributed execution.

Classes:

RemoteTaskManager ¤
RemoteTaskManager(default_timeout: float = 300.0)

              flowchart TD
              digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager[RemoteTaskManager]
              digitalkin.core.task_manager.base_task_manager.BaseTaskManager[BaseTaskManager]

                              digitalkin.core.task_manager.base_task_manager.BaseTaskManager --> digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager
                


              click digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager href "" "digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager"
              click digitalkin.core.task_manager.base_task_manager.BaseTaskManager href "" "digitalkin.core.task_manager.base_task_manager.BaseTaskManager"
            

Task manager for distributed/remote execution.

Only manages task metadata and signals - actual execution happens in remote workers. Suitable for horizontally scaled deployments with Taskiq/Celery workers.

Parameters:

  • default_timeout ¤
    (float, default: 300.0 ) –

    Default timeout for task operations in seconds

Methods:

  • __aenter__

    Enter async context manager.

  • __aexit__

    Exit async context manager and clean up resources.

  • cancel_all_tasks

    Cancel all running tasks.

  • cancel_task

    Cancel a task with graceful shutdown and fallback.

  • clean_session

    Force cleanup of task session, cancelling the task if still running.

  • create_task

    Register task for remote execution (metadata only).

  • send_signal

    Send signal to a specific task.

  • shutdown

    Graceful shutdown of all tasks.

Attributes:

max_concurrent_tasks property writable ¤
max_concurrent_tasks: int

Maximum number of concurrent tasks.

running_tasks property ¤
running_tasks: set[str]

Get IDs of currently running tasks.

task_count property ¤
task_count: int

Number of active tasks (pending or running).

__aenter__ async ¤
__aenter__() -> Self

Enter async context manager.

Returns:

  • Self

    Self for use in async with statements

__aexit__ async ¤
__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit async context manager and clean up resources.

Parameters:

  • exc_type ¤ (type[BaseException] | None) –

    Exception type if an exception occurred

  • exc_val ¤ (BaseException | None) –

    Exception value if an exception occurred

  • exc_tb ¤ (TracebackType | None) –

    Exception traceback if an exception occurred

cancel_all_tasks async ¤
cancel_all_tasks(
    mission_id: str, timeout: float | None = None
) -> dict[str, bool | BaseException]

Cancel all running tasks.

Parameters:

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float | None, default: None ) –

    Optional timeout for cancellation

Returns:

cancel_task async ¤
cancel_task(task_id: str, mission_id: str, timeout: float | None = None) -> bool

Cancel a task with graceful shutdown and fallback.

Parameters:

  • task_id ¤ (str) –

    The ID of the task to cancel

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float | None, default: None ) –

    Optional timeout for cancellation

Returns:

  • bool

    True if the task was cancelled successfully, False otherwise

clean_session async ¤
clean_session(task_id: str, mission_id: str) -> bool

Force cleanup of task session, cancelling the task if still running.

Parameters:

  • task_id ¤ (str) –

    The ID of the task

  • mission_id ¤ (str) –

    The ID of the mission

Returns:

  • bool

    True if the task session was cleaned successfully, False otherwise.

create_task async ¤
create_task(
    task_id: str, mission_id: str, module: BaseModule, coro: Coroutine[Any, Any, None]
) -> None

Register task for remote execution (metadata only).

Creates TaskSession for signal handling and monitoring, but doesn't execute the coroutine. The coroutine will be recreated and executed by a remote worker.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier

  • module ¤ (BaseModule) –

    Module instance for metadata (not executed here)

  • coro ¤ (Coroutine[Any, Any, None]) –

    Coroutine (will be closed - execution happens in worker)

Raises:

send_signal async ¤

Send signal to a specific task.

Parameters:

  • task_id ¤ (str) –

    The ID of the task

  • mission_id ¤ (str) –

    The ID of the mission

  • signal_type ¤ (str) –

    Type of signal to send

  • payload ¤ (dict) –

    Signal payload

Returns:

  • bool

    True if the signal was sent successfully, False otherwise

shutdown async ¤
shutdown(mission_id: str, timeout: float = 30.0) -> None

Graceful shutdown of all tasks.

Parameters:

  • mission_id ¤ (str) –

    The ID of the mission

  • timeout ¤ (float, default: 30.0 ) –

    Timeout for shutdown operations

task_executor ¤

Task executor for running tasks with full lifecycle management.

Classes:

  • TaskExecutor

    Executes tasks with the supervisor pattern (main + signal listener).

TaskExecutor ¤

Executes tasks with the supervisor pattern (main + signal listener).

Pure execution logic - no task registry or orchestration. Used by workers to run distributed tasks or by TaskManager for local execution.

Methods:

  • execute_task

    Execute a task using the supervisor pattern.

execute_task async staticmethod ¤
execute_task(
    task_id: str, mission_id: str, coro: Coroutine[Any, Any, None], session: TaskSession
) -> Task[None]

Execute a task using the supervisor pattern.

Runs two concurrent sub-tasks: - Main coroutine (the actual work) - Signal listener (watches for stop/cancel signals)

The first task to complete determines the outcome.

Parameters:

  • task_id ¤ (str) –

    Unique identifier for the task

  • mission_id ¤ (str) –

    Mission identifier for the task

  • coro ¤ (Coroutine[Any, Any, None]) –

    The coroutine to execute (module.start(...))

  • session ¤ (TaskSession) –

    TaskSession for state management

Returns:

  • Task[None]

    asyncio.Task: The supervisor task managing the lifecycle

task_session ¤

Task session easing task lifecycle management.

Classes:

  • TaskSession

    Task Session with lifecycle management.

TaskSession ¤
TaskSession(
    task_id: str, mission_id: str, module: BaseModule, queue_maxsize: int = 1000
)

Task Session with lifecycle management.

The Session defines the whole lifecycle of a task as an ephemeral context.

Parameters:

  • task_id ¤
    (str) –

    Unique task identifier

  • mission_id ¤
    (str) –

    Mission identifier

  • module ¤
    (BaseModule) –

    Module instance

  • queue_maxsize ¤
    (int, default: 1000 ) –

    Maximum size for the queue (0 = unlimited)

Methods:

Attributes:

cancelled property ¤
cancelled: bool

Task cancellation status.

session_ids property ¤
session_ids: dict[str, str]

Get all session IDs from module context for structured logging.

setup_id property ¤
setup_id: str

Get setup_id from module context.

setup_version_id property ¤
setup_version_id: str

Get setup_version_id from module context.

stream_closed property ¤
stream_closed: bool

Check if stream termination was signaled.

cleanup async ¤
cleanup() -> None

Clean up task session resources.

This method is idempotent - safe to call multiple times. Second and subsequent calls are no-ops.

This includes: - Clearing queue to free memory - Cleaning up module context services - Stopping module - Clearing module reference

close_stream ¤
close_stream() -> None

Signal that the stream should terminate.

listen_signals async ¤
listen_signals() -> None

Signal listener for cancel signals via TaskManagerStrategy.

Subscribes to signal updates for this task_id and processes cancel signals.

Raises:

  • CancelledError

    If task is cancelled during signal listening.

record_exception ¤
record_exception(exc: Exception) -> None

Record exception details for logging.

Parameters:

  • exc ¤ (Exception) –

    The exception that caused the task to fail.

grpc_servers ¤

This package contains the gRPC server and client implementations.

Modules:

  • module_server

    Module gRPC server implementation for DigitalKin.

  • module_servicer

    Module servicer implementation for DigitalKin.

  • utils

    gRPC servers utilities package.

module_server ¤

Module gRPC server implementation for DigitalKin.

Classes:

ModuleServer ¤

ModuleServer(
    module_class: type[BaseModule],
    client_config: ClientConfig | None = None,
    interceptors: Sequence[Any] | None = None,
)

              flowchart TD
              digitalkin.grpc_servers.module_server.ModuleServer[ModuleServer]
              digitalkin.grpc_servers._base_server.BaseServer[BaseServer]

                              digitalkin.grpc_servers._base_server.BaseServer --> digitalkin.grpc_servers.module_server.ModuleServer
                


              click digitalkin.grpc_servers.module_server.ModuleServer href "" "digitalkin.grpc_servers.module_server.ModuleServer"
              click digitalkin.grpc_servers._base_server.BaseServer href "" "digitalkin.grpc_servers._base_server.BaseServer"
            

gRPC server for a DigitalKin module.

This server exposes the module's functionality through the ModuleService gRPC interface. It can optionally register itself with a Registry server.

Attributes:

  • module

    The module instance being served.

  • server_config

    Server configuration.

  • client_config

    Setup client configuration.

  • module_servicer (ModuleServicer | None) –

    The gRPC servicer handling module requests.

Parameters:

  • module_class ¤
    (type[BaseModule]) –

    The module instance to be served.

  • client_config ¤
    (ClientConfig | None, default: None ) –

    Client configuration used by services and registry connection.

  • interceptors ¤
    (Sequence[Any] | None, default: None ) –

    Optional sequence of gRPC server interceptors.

Methods:

  • await_termination

    Wait for the async server to terminate.

  • register_servicer

    Register a servicer with the gRPC server and track it for reflection.

  • start

    Start the module server and register with the registry if configured.

  • start_async

    Start the module server and register with the registry if configured.

  • stop

    Stop the gRPC server and close all cached gRPC client channels.

  • stop_async

    Stop the module server with async cleanup.

  • wait_for_termination

    Wait for the server to terminate.

await_termination async ¤
await_termination() -> None

Wait for the async server to terminate.

This method should only be used with async servers.

register_servicer ¤
register_servicer(
    servicer: T,
    add_to_server_fn: Callable[[T, GrpcServer], None],
    service_descriptor: ServiceDescriptor | None = None,
    service_names: list[str] | None = None,
) -> None

Register a servicer with the gRPC server and track it for reflection.

Parameters:

  • servicer ¤
    (T) –

    The servicer implementation instance

  • add_to_server_fn ¤
    (Callable[[T, GrpcServer], None]) –

    The function to add the servicer to the server

  • service_descriptor ¤
    (ServiceDescriptor | None, default: None ) –

    Optional service descriptor (pb2 DESCRIPTOR)

  • service_names ¤
    (list[str] | None, default: None ) –

    Optional explicit list of service full names

Raises:

start ¤
start() -> None

Start the module server and register with the registry if configured.

start_async async ¤
start_async() -> None

Start the module server and register with the registry if configured.

stop ¤
stop(grace: float | None = None) -> None

Stop the gRPC server and close all cached gRPC client channels.

Parameters:

  • grace ¤
    (float | None, default: None ) –

    Optional grace period in seconds for existing RPCs to complete.

stop_async async ¤
stop_async(grace: float | None = None) -> None

Stop the module server with async cleanup.

Deregisters from registry and stops the server. Modules also become inactive when they stop sending heartbeats as a fallback.

wait_for_termination ¤
wait_for_termination() -> None

Wait for the server to terminate.

In synchronous mode, this blocks until the server is terminated. In asynchronous mode, a warning is logged suggesting to use await_termination.

module_servicer ¤

Module servicer implementation for DigitalKin.

Classes:

ModuleServicer ¤

ModuleServicer(module_class: type[BaseModule])

              flowchart TD
              digitalkin.grpc_servers.module_servicer.ModuleServicer[ModuleServicer]
              digitalkin.utils.arg_parser.ArgParser[ArgParser]

                              digitalkin.utils.arg_parser.ArgParser --> digitalkin.grpc_servers.module_servicer.ModuleServicer
                


              click digitalkin.grpc_servers.module_servicer.ModuleServicer href "" "digitalkin.grpc_servers.module_servicer.ModuleServicer"
              click digitalkin.utils.arg_parser.ArgParser href "" "digitalkin.utils.arg_parser.ArgParser"
            

Implementation of the ModuleService.

This servicer handles interactions with a DigitalKin module.

Attributes:

  • module

    The module instance being served.

  • active_jobs

    Dictionary tracking active module jobs.

Parameters:

  • module_class ¤
    (type[BaseModule]) –

    The module type to serve.

Classes:

  • HelpAction

    Custom HelpAction to display subparsers helps too.

Methods:

HelpAction ¤

              flowchart TD
              digitalkin.grpc_servers.module_servicer.ModuleServicer.HelpAction[HelpAction]

              

              click digitalkin.grpc_servers.module_servicer.ModuleServicer.HelpAction href "" "digitalkin.grpc_servers.module_servicer.ModuleServicer.HelpAction"
            

Custom HelpAction to display subparsers helps too.

Methods:

  • __call__

    Override the HelpActions as it doesn't handle subparser well.

__call__ ¤
__call__(
    parser: ArgumentParser,
    namespace: Namespace,
    values: str | Sequence[Any] | None,
    option_string: str | None = None,
) -> None

Override the HelpActions as it doesn't handle subparser well.

ConfigSetupModule async ¤
ConfigSetupModule(
    request: ConfigSetupModuleRequest, context: ServicerContext
) -> ConfigSetupModuleResponse

Configure the module setup.

Parameters:

  • request ¤
    (ConfigSetupModuleRequest) –

    The configuration request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • ConfigSetupModuleResponse

    A response indicating success or failure.

Raises:

  • ServicerError

    if the setup data is not returned or job creation fails.

GetConfigSetupModule async ¤
GetConfigSetupModule(
    request: GetConfigSetupModuleRequest, context: ServicerContext
) -> GetConfigSetupModuleResponse

Get information about the module's setup and configuration.

Parameters:

  • request ¤
    (GetConfigSetupModuleRequest) –

    The get module setup request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetConfigSetupModuleResponse

    A response with the module's setup information.

GetModuleCost async ¤
GetModuleCost(
    request: GetModuleCostRequest, context: ServicerContext
) -> GetModuleCostResponse

Get information about the module's cost configuration.

Parameters:

  • request ¤
    (GetModuleCostRequest) –

    The get module cost request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetModuleCostResponse

    A response with the module's cost schema.

GetModuleInput async ¤
GetModuleInput(
    request: GetModuleInputRequest, context: ServicerContext
) -> GetModuleInputResponse

Get information about the module's expected input.

Parameters:

  • request ¤
    (GetModuleInputRequest) –

    The get module input request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetModuleInputResponse

    A response with the module's input schema.

GetModuleOutput async ¤
GetModuleOutput(
    request: GetModuleOutputRequest, context: ServicerContext
) -> GetModuleOutputResponse

Get information about the module's expected output.

Parameters:

  • request ¤
    (GetModuleOutputRequest) –

    The get module output request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetModuleOutputResponse

    A response with the module's output schema.

GetModuleSecret async ¤
GetModuleSecret(
    request: GetModuleSecretRequest, context: ServicerContext
) -> GetModuleSecretResponse

Get information about the module's secrets.

Parameters:

  • request ¤
    (GetModuleSecretRequest) –

    The get module secret request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetModuleSecretResponse

    A response with the module's secret schema.

GetModuleSelectInput async ¤
GetModuleSelectInput(
    request: GetModuleSelectInputRequest, context: ServicerContext
) -> GetModuleSelectInputResponse

Get the trigger selection schema for the module.

Parameters:

  • request ¤
    (GetModuleSelectInputRequest) –

    The get module select input request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetModuleSelectInputResponse

    A response with the module's select input schema.

GetModuleSetup async ¤
GetModuleSetup(
    request: GetModuleSetupRequest, context: ServicerContext
) -> GetModuleSetupResponse

Get information about the module's setup and configuration.

Parameters:

  • request ¤
    (GetModuleSetupRequest) –

    The get module setup request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • GetModuleSetupResponse

    A response with the module's setup information.

StartModule async ¤
StartModule(
    request: StartModuleRequest, context: ServicerContext
) -> AsyncGenerator[StartModuleResponse, Any]

Start a module execution.

Parameters:

  • request ¤
    (StartModuleRequest) –

    Iterator of start module requests.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Yields:

Raises:

StopModule async ¤
StopModule(request: StopModuleRequest, context: ServicerContext) -> StopModuleResponse

Stop a running module execution.

Parameters:

  • request ¤
    (StopModuleRequest) –

    The stop module request.

  • context ¤
    (ServicerContext) –

    The gRPC context.

Returns:

  • StopModuleResponse

    A response indicating success or failure.

shutdown async ¤
shutdown() -> None

Release servicer-level resources (GrpcSetup channel, registry cache).

utils ¤

gRPC servers utilities package.

Modules:

exceptions ¤

Exceptions for the DigitalKin gRPC package.

Classes:

ConfigurationError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.ConfigurationError[ConfigurationError]
              digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

                              digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ConfigurationError
                                digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
                



              click digitalkin.grpc_servers.utils.exceptions.ConfigurationError href "" "digitalkin.grpc_servers.utils.exceptions.ConfigurationError"
              click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Error related to server configuration.

DigitalKinError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

              

              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Base exception for all DigitalKin errors.

ReflectionError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.ReflectionError[ReflectionError]
              digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

                              digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ReflectionError
                                digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
                



              click digitalkin.grpc_servers.utils.exceptions.ReflectionError href "" "digitalkin.grpc_servers.utils.exceptions.ReflectionError"
              click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Error related to gRPC reflection service.

SecurityError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.SecurityError[SecurityError]
              digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

                              digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.SecurityError
                                digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
                



              click digitalkin.grpc_servers.utils.exceptions.SecurityError href "" "digitalkin.grpc_servers.utils.exceptions.SecurityError"
              click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Error related to security configuration.

ServerError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

                              digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
                


              click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Base class for server-related errors.

ServerStateError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.ServerStateError[ServerStateError]
              digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

                              digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ServerStateError
                                digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
                



              click digitalkin.grpc_servers.utils.exceptions.ServerStateError href "" "digitalkin.grpc_servers.utils.exceptions.ServerStateError"
              click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Error related to server state (e.g., already started, not started).

ServicerError ¤

              flowchart TD
              digitalkin.grpc_servers.utils.exceptions.ServicerError[ServicerError]
              digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
              digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]

                              digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ServicerError
                                digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
                



              click digitalkin.grpc_servers.utils.exceptions.ServicerError href "" "digitalkin.grpc_servers.utils.exceptions.ServicerError"
              click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
              click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
            

Error related to servicer operations.

grpc_client_wrapper ¤

Client wrapper to ease channel creation with specific ServerConfig.

Classes:

GrpcClientWrapper ¤

gRPC client shared by the different services.

Subclasses should set the service_name class attribute to identify the gRPC service in logs (e.g., "SetupService", "RegistryService").

Channels are cached at the class level and ref-counted. gRPC HTTP/2 channels natively multiplex concurrent streams on a single connection, so sharing a channel across tasks is safe and efficient.

Methods:

  • close

    Release this instance's gRPC channel ref. Subclasses override to release extra resources.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release this instance's gRPC channel ref. Subclasses override to release extra resources.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

grpc_error_handler ¤

Shared error handling utilities for gRPC services.

Classes:

GrpcErrorHandlerMixin ¤

Mixin class providing common gRPC error handling functionality.

Methods:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤ (str) –

    Name of the operation being performed.

  • service_error_class ¤ (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

utility_schema_extender ¤

Utility schema extender for gRPC API responses.

This module extends module schemas with SDK utility protocols for API responses.

Classes:

UtilitySchemaExtender ¤

Extends module schemas with SDK utility protocols for API responses.

This class provides methods to create extended Pydantic models that include both user-defined protocols and SDK utility protocols in their schemas.

Methods:

create_extended_input_model classmethod ¤
create_extended_input_model(base_model: type[DataModel]) -> type[DataModel]

Create an extended input model that includes utility input protocols.

Parameters:

  • base_model ¤ (type[DataModel]) –

    The module's input_format class (a DataModel subclass).

Returns:

  • type[DataModel]

    A new DataModel subclass with root typed as Union[original_types, utility_types],

  • type[DataModel]

    and includes cost_limits field for cost control.

create_extended_output_model classmethod ¤
create_extended_output_model(base_model: type[DataModel]) -> type[DataModel]

Create an extended output model that includes utility output protocols.

Parameters:

  • base_model ¤ (type[DataModel]) –

    The module's output_format class (a DataModel subclass).

Returns:

  • type[DataModel]

    A new DataModel subclass with root typed as Union[original_types, utility_types].

logger ¤

This module sets up a logger.

Classes:

  • ColorJSONFormatter

    Color JSON formatter for development (pretty-printed with colors).

  • PlainJSONFormatter

    Plain JSON formatter for log files (no ANSI colors, compact JSON).

Functions:

  • add_file_handler

    Add a rotating file handler to a logger if DIGITALKIN_LOG_DIR is set.

  • setup_logger

    Set up a logger with the ColorJSONFormatter.

ColorJSONFormatter ¤

ColorJSONFormatter(*, is_production: bool = False)

              flowchart TD
              digitalkin.logger.ColorJSONFormatter[ColorJSONFormatter]

              

              click digitalkin.logger.ColorJSONFormatter href "" "digitalkin.logger.ColorJSONFormatter"
            

Color JSON formatter for development (pretty-printed with colors).

Parameters:

  • is_production ¤

    (bool, default: False ) –

    Whether the application is running in production.

Methods:

  • format

    Format the log record as colored JSON for development.

format ¤

format(record: LogRecord) -> str

Format the log record as colored JSON for development.

Parameters:

Returns:

  • str ( str ) –

    The colored JSON formatted log record.

PlainJSONFormatter ¤


              flowchart TD
              digitalkin.logger.PlainJSONFormatter[PlainJSONFormatter]

              

              click digitalkin.logger.PlainJSONFormatter href "" "digitalkin.logger.PlainJSONFormatter"
            

Plain JSON formatter for log files (no ANSI colors, compact JSON).

Methods:

  • format

    Format the log record as compact JSON for file output.

format ¤

format(record: LogRecord) -> str

Format the log record as compact JSON for file output.

Parameters:

Returns:

  • str ( str ) –

    The compact JSON formatted log record.

add_file_handler ¤

add_file_handler(logger: Logger) -> None

Add a rotating file handler to a logger if DIGITALKIN_LOG_DIR is set.

Only creates log files when the environment variable is explicitly set and points to an existing directory. Attaches a :class:RotatingFileHandler (10 MB, 5 backups) with :class:PlainJSONFormatter at DEBUG level.

Parameters:

  • logger ¤

    (Logger) –

    The logger to attach the file handler to.

setup_logger ¤

setup_logger(
    name: str,
    level: int = INFO,
    additional_loggers: dict[str, int] | None = None,
    *,
    is_production: bool | None = None,
    configure_root: bool = True,
) -> Logger

Set up a logger with the ColorJSONFormatter.

Parameters:

  • name ¤

    (str) –

    Name of the logger to create

  • level ¤

    (int, default: INFO ) –

    Logging level (default: logging.INFO)

  • is_production ¤

    (bool | None, default: None ) –

    Whether running in production. If None, checks RAILWAY_SERVICE_NAME env var

  • configure_root ¤

    (bool, default: True ) –

    Whether to configure root logger (default: True)

  • additional_loggers ¤

    (dict[str, int] | None, default: None ) –

    Dict of additional logger names and their levels to configure

Returns:

  • Logger

    logging.Logger: Configured logger instance

mixins ¤

Mixin definitions.

Modules:

  • agui_mixin

    AG-UI event streaming mixin for DigitalKin modules.

  • base_mixin

    Simple toolkit class with basic and simple API access in the Triggers.

  • callback_mixin

    User callback to send a message from the Trigger.

  • chat_history_mixin

    Context mixins providing ergonomic access to service strategies.

  • cost_mixin

    Cost Mixin to ease trigger deveolpment.

  • file_history_mixin

    Context mixins providing ergonomic access to service strategies.

  • filesystem_mixin

    Filesystem Mixin to ease filesystem use.

  • logger_mixin

    Logger Mixin to ease and merge every logs.

  • storage_mixin

    Storage Mixin to ease storage access in Triggers.

Classes:

  • AgUiMixin

    Mixin for converting agent events to AG-UI protocol and sending them.

  • BaseMixin

    Base Mixin to access to minimum Module Context functionnalities in the Triggers.

  • CostMixin

    Mixin providing cost tracking operations through the cost strategy.

  • FilesystemMixin

    Mixin providing filesystem operations through the filesystem strategy.

  • LoggerMixin

    Mixin providing callback operations through the callbacks strategy.

  • StorageMixin

    Mixin providing storage operations through the storage strategy.

AgUiMixin ¤

AgUiMixin()

Mixin for converting agent events to AG-UI protocol and sending them.

This mixin is a stateless emitter: each handler reads IDs from the event and emits the corresponding AG-UI event(s). The adapter is responsible for generating IDs and managing event lifecycle (start/complete sequences).

Usage::

class MyTrigger(BaseTrigger, AgUiMixin):
    async def execute(self, context, input_data):
        async for event in agent.run(input_data.message, stream=True):
            await self.agui_send_message(context, event)

Methods:

  • send_message

    Convert agent event to AG-UI protocol and send via context callbacks.

send_message async ¤

send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

BaseMixin ¤

BaseMixin()

              flowchart TD
              digitalkin.mixins.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.BaseMixin
                


              click digitalkin.mixins.BaseMixin href "" "digitalkin.mixins.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Base Mixin to access to minimum Module Context functionnalities in the Triggers.

Methods:

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤
    (str) –

    Name of the cost configuration to use.

  • quantity ¤
    (float) –

    Quantity of units consumed.

append_files_history async ¤

append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤

clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤

flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤

get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤
    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

load_file_history async ¤

load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤

log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤

log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤

log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤

log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤

send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤

store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤

update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤

upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

CostMixin ¤

Mixin providing cost tracking operations through the cost strategy.

This mixin wraps cost strategy calls to provide a cleaner API for cost tracking in trigger handlers. Cost failures are non-critical and never crash tasks.

Methods:

  • add_cost

    Add a cost entry using the cost strategy.

  • get_cost

    Get cost entries for a specific name.

  • get_costs

    Get filtered cost entries.

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤
    (str) –

    Name of the cost configuration to use.

  • quantity ¤
    (float) –

    Quantity of units consumed.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤

get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤
    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

FilesystemMixin ¤

Mixin providing filesystem operations through the filesystem strategy.

This mixin wraps filesystem strategy calls to provide a cleaner API for file operations in trigger handlers.

Methods:

  • get_file

    Retrieve a file by ID with the content.

  • upload_files

    Upload files using the filesystem strategy.

get_file async staticmethod ¤

Retrieve a file by ID with the content.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the filesystem strategy

  • file_id ¤
    (str) –

    Unique identifier for the file

Returns:

Raises:

  • FilesystemServiceError

    If file retrieval fails

upload_files async staticmethod ¤

Upload files using the filesystem strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the filesystem strategy

  • files ¤
    (list[Any]) –

    List of files to upload

Returns:

Raises:

  • FilesystemServiceError

    If upload operation fails

LoggerMixin ¤

Mixin providing callback operations through the callbacks strategy.

This mixin wraps callback strategy calls to provide a cleaner API for logging and messaging in trigger handlers.

Methods:

  • log_debug

    Log debug message using the callbacks strategy.

  • log_error

    Log error message using the callbacks strategy.

  • log_info

    Log info message using the callbacks strategy.

  • log_warning

    Log warning message using the callbacks strategy.

log_debug staticmethod ¤

log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤

log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤

log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤

log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

StorageMixin ¤

Mixin providing storage operations through the storage strategy.

This mixin wraps storage strategy calls to provide a cleaner API for trigger handlers.

Methods:

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

store_storage async staticmethod ¤

store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤

update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤

upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

agui_mixin ¤

AG-UI event streaming mixin for DigitalKin modules.

This mixin provides utilities to convert framework-agnostic agent events into AG-UI protocol events and send them through the module context callbacks.

The mixin is a stateless emitter: it receives events with all necessary info (including IDs) and emits the corresponding AG-UI protocol events. All state management (ID generation, lifecycle tracking) belongs in the adapter layer.

Classes:

  • AgUiMixin

    Mixin for converting agent events to AG-UI protocol and sending them.

AgUiMixin ¤

AgUiMixin()

Mixin for converting agent events to AG-UI protocol and sending them.

This mixin is a stateless emitter: each handler reads IDs from the event and emits the corresponding AG-UI event(s). The adapter is responsible for generating IDs and managing event lifecycle (start/complete sequences).

Usage::

class MyTrigger(BaseTrigger, AgUiMixin):
    async def execute(self, context, input_data):
        async for event in agent.run(input_data.message, stream=True):
            await self.agui_send_message(context, event)

Methods:

  • send_message

    Convert agent event to AG-UI protocol and send via context callbacks.

send_message async ¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

base_mixin ¤

Simple toolkit class with basic and simple API access in the Triggers.

Classes:

  • BaseMixin

    Base Mixin to access to minimum Module Context functionnalities in the Triggers.

BaseMixin ¤

BaseMixin()

              flowchart TD
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                


              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Base Mixin to access to minimum Module Context functionnalities in the Triggers.

Methods:

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤
    (str) –

    Name of the cost configuration to use.

  • quantity ¤
    (float) –

    Quantity of units consumed.

append_files_history async ¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤
clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤
flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤
get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤
    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

load_file_history async ¤
load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

callback_mixin ¤

User callback to send a message from the Trigger.

.. deprecated:: Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.

Classes:

  • UserMessageMixin

    Mixin providing callback operations through the callbacks.

UserMessageMixin ¤


              flowchart TD
              digitalkin.mixins.callback_mixin.UserMessageMixin[UserMessageMixin]

              

              click digitalkin.mixins.callback_mixin.UserMessageMixin href "" "digitalkin.mixins.callback_mixin.UserMessageMixin"
            

Mixin providing callback operations through the callbacks.

.. deprecated:: Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.

Methods:

__init_subclass__ ¤
__init_subclass__(**kwargs: Any) -> None

Deprecated warning.

send_message async staticmethod ¤
send_message(context: ModuleContext, output: OutputModelT) -> None

Send a message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy.

  • output ¤
    (OutputModelT) –

    Message to send with the Module defined output Type.

chat_history_mixin ¤

Context mixins providing ergonomic access to service strategies.

.. deprecated:: Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.

Classes:

  • ChatHistoryMixin

    Mixin providing chat history operations through storage strategy.

ChatHistoryMixin ¤

ChatHistoryMixin()

              flowchart TD
              digitalkin.mixins.chat_history_mixin.ChatHistoryMixin[ChatHistoryMixin]
              digitalkin.mixins.callback_mixin.UserMessageMixin[UserMessageMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.callback_mixin.UserMessageMixin --> digitalkin.mixins.chat_history_mixin.ChatHistoryMixin
                
                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.chat_history_mixin.ChatHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.chat_history_mixin.ChatHistoryMixin
                


              click digitalkin.mixins.chat_history_mixin.ChatHistoryMixin href "" "digitalkin.mixins.chat_history_mixin.ChatHistoryMixin"
              click digitalkin.mixins.callback_mixin.UserMessageMixin href "" "digitalkin.mixins.callback_mixin.UserMessageMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Mixin providing chat history operations through storage strategy.

.. deprecated:: Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.

Methods:

__init_subclass__ ¤
__init_subclass__(**kwargs: Any) -> None

Deprecated warning.

append_chat_history_message async ¤
append_chat_history_message(context: ModuleContext, role: Role, content: Any) -> None

Append a message to chat history.

The message is added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_CHAT_HISTORY_FLUSH_THRESHOLD) or flush_chat_history().

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

  • role ¤
    (Role) –

    Message role (user, assistant, system).

  • content ¤
    (Any) –

    Message content.

clear_ch_mission_cache ¤
clear_ch_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context identifying the mission to clear.

flush_chat_history async ¤
flush_chat_history(context: ModuleContext) -> None

Flush the current mission's dirty chat history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

load_chat_history async ¤
load_chat_history(context: ModuleContext) -> ChatHistory

Load chat history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • ChatHistory

    Chat history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

save_send_message async ¤
save_send_message(context: ModuleContext, output: OutputModelT, role: Role) -> None

Save output to chat history and send response to the module request.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

  • role ¤
    (Role) –

    Message role (user, assistant, system).

  • output ¤
    (OutputModelT) –

    Message content as Pydantic Class.

send_message async staticmethod ¤
send_message(context: ModuleContext, output: OutputModelT) -> None

Send a message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy.

  • output ¤
    (OutputModelT) –

    Message to send with the Module defined output Type.

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

cost_mixin ¤

Cost Mixin to ease trigger deveolpment.

Classes:

  • CostMixin

    Mixin providing cost tracking operations through the cost strategy.

CostMixin ¤

Mixin providing cost tracking operations through the cost strategy.

This mixin wraps cost strategy calls to provide a cleaner API for cost tracking in trigger handlers. Cost failures are non-critical and never crash tasks.

Methods:

  • add_cost

    Add a cost entry using the cost strategy.

  • get_cost

    Get cost entries for a specific name.

  • get_costs

    Get filtered cost entries.

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤
    (str) –

    Name of the cost configuration to use.

  • quantity ¤
    (float) –

    Quantity of units consumed.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤
get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤
    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

file_history_mixin ¤

Context mixins providing ergonomic access to service strategies.

This module provides mixins that wrap service strategy calls with cleaner APIs, following Django/FastAPI patterns where context is passed explicitly to each method.

Classes:

  • FileHistoryMixin

    Mixin providing file history operations through storage strategy.

FileHistoryMixin ¤

FileHistoryMixin()

              flowchart TD
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                


              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Mixin providing file history operations through storage strategy.

File histories are cached in memory after first load to avoid redundant gRPC reads. Known-persisted keys use update_storage (1 call) instead of upsert_storage (2 calls).

Writes are batched: files accumulate in the cache and are flushed when the batch threshold is reached or flush_file_history() is called.

Methods:

append_files_history async ¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤
clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤
flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

load_file_history async ¤
load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

filesystem_mixin ¤

Filesystem Mixin to ease filesystem use.

Classes:

  • FilesystemMixin

    Mixin providing filesystem operations through the filesystem strategy.

FilesystemMixin ¤

Mixin providing filesystem operations through the filesystem strategy.

This mixin wraps filesystem strategy calls to provide a cleaner API for file operations in trigger handlers.

Methods:

  • get_file

    Retrieve a file by ID with the content.

  • upload_files

    Upload files using the filesystem strategy.

get_file async staticmethod ¤

Retrieve a file by ID with the content.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the filesystem strategy

  • file_id ¤
    (str) –

    Unique identifier for the file

Returns:

Raises:

  • FilesystemServiceError

    If file retrieval fails

upload_files async staticmethod ¤

Upload files using the filesystem strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the filesystem strategy

  • files ¤
    (list[Any]) –

    List of files to upload

Returns:

Raises:

  • FilesystemServiceError

    If upload operation fails

logger_mixin ¤

Logger Mixin to ease and merge every logs.

Classes:

  • LoggerMixin

    Mixin providing callback operations through the callbacks strategy.

LoggerMixin ¤

Mixin providing callback operations through the callbacks strategy.

This mixin wraps callback strategy calls to provide a cleaner API for logging and messaging in trigger handlers.

Methods:

  • log_debug

    Log debug message using the callbacks strategy.

  • log_error

    Log error message using the callbacks strategy.

  • log_info

    Log info message using the callbacks strategy.

  • log_warning

    Log warning message using the callbacks strategy.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

storage_mixin ¤

Storage Mixin to ease storage access in Triggers.

Classes:

  • StorageMixin

    Mixin providing storage operations through the storage strategy.

StorageMixin ¤

Mixin providing storage operations through the storage strategy.

This mixin wraps storage strategy calls to provide a cleaner API for trigger handlers.

Methods:

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

models ¤

This package contains the models for DigitalKin.

Modules:

  • core

    Core models.

  • events

    Agent run event models for DigitalKin.

  • grpc_servers

    Base gRPC server and client models.

  • module

    This module contains the models for the modules.

  • services

    This module contains the models for the services.

  • settings

    This package contain settings of sdk.

Classes:

AgentRunEvent ¤


              flowchart TD
              digitalkin.models.AgentRunEvent[AgentRunEvent]

              

              click digitalkin.models.AgentRunEvent href "" "digitalkin.models.AgentRunEvent"
            

Agent run event types.

BaseAgentRunEvent ¤


              flowchart TD
              digitalkin.models.BaseAgentRunEvent[BaseAgentRunEvent]

              

              click digitalkin.models.BaseAgentRunEvent href "" "digitalkin.models.BaseAgentRunEvent"
            

Base class for all agent run events.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

Module ¤


              flowchart TD
              digitalkin.models.Module[Module]

              

              click digitalkin.models.Module href "" "digitalkin.models.Module"
            

Module model.

ModuleStatus ¤


              flowchart TD
              digitalkin.models.ModuleStatus[ModuleStatus]

              

              click digitalkin.models.ModuleStatus href "" "digitalkin.models.ModuleStatus"
            

Possible module's state.

ReasoningCompletedEvent ¤


              flowchart TD
              digitalkin.models.ReasoningCompletedEvent[ReasoningCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningCompletedEvent
                


              click digitalkin.models.ReasoningCompletedEvent href "" "digitalkin.models.ReasoningCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a reasoning phase completes.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningContentDeltaEvent ¤


              flowchart TD
              digitalkin.models.ReasoningContentDeltaEvent[ReasoningContentDeltaEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningContentDeltaEvent
                


              click digitalkin.models.ReasoningContentDeltaEvent href "" "digitalkin.models.ReasoningContentDeltaEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted during extended thinking/reasoning phases.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningStartedEvent ¤


              flowchart TD
              digitalkin.models.ReasoningStartedEvent[ReasoningStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningStartedEvent
                


              click digitalkin.models.ReasoningStartedEvent href "" "digitalkin.models.ReasoningStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a reasoning phase starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningStepEvent ¤


              flowchart TD
              digitalkin.models.ReasoningStepEvent[ReasoningStepEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningStepEvent
                


              click digitalkin.models.ReasoningStepEvent href "" "digitalkin.models.ReasoningStepEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted for intermediate reasoning steps.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunCompletedEvent ¤


              flowchart TD
              digitalkin.models.RunCompletedEvent[RunCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunCompletedEvent
                


              click digitalkin.models.RunCompletedEvent href "" "digitalkin.models.RunCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run completes successfully.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunContentEvent ¤


              flowchart TD
              digitalkin.models.RunContentEvent[RunContentEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunContentEvent
                


              click digitalkin.models.RunContentEvent href "" "digitalkin.models.RunContentEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when the agent produces content (text, reasoning, etc.).

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunErrorEvent ¤


              flowchart TD
              digitalkin.models.RunErrorEvent[RunErrorEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunErrorEvent
                


              click digitalkin.models.RunErrorEvent href "" "digitalkin.models.RunErrorEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run encounters an error.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunStartedEvent ¤


              flowchart TD
              digitalkin.models.RunStartedEvent[RunStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunStartedEvent
                


              click digitalkin.models.RunStartedEvent href "" "digitalkin.models.RunStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallCompletedEvent ¤


              flowchart TD
              digitalkin.models.ToolCallCompletedEvent[ToolCallCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ToolCallCompletedEvent
                


              click digitalkin.models.ToolCallCompletedEvent href "" "digitalkin.models.ToolCallCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call completes successfully.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallErrorEvent ¤


              flowchart TD
              digitalkin.models.ToolCallErrorEvent[ToolCallErrorEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ToolCallErrorEvent
                


              click digitalkin.models.ToolCallErrorEvent href "" "digitalkin.models.ToolCallErrorEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call encounters an error.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallStartedEvent ¤


              flowchart TD
              digitalkin.models.ToolCallStartedEvent[ToolCallStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ToolCallStartedEvent
                


              click digitalkin.models.ToolCallStartedEvent href "" "digitalkin.models.ToolCallStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolInfo ¤


              flowchart TD
              digitalkin.models.ToolInfo[ToolInfo]

              

              click digitalkin.models.ToolInfo href "" "digitalkin.models.ToolInfo"
            

Information about a tool call.

core ¤

Core models.

Modules:

job_manager_models ¤

Job manager models.

Classes:

BackpressureStrategy ¤

              flowchart TD
              digitalkin.models.core.job_manager_models.BackpressureStrategy[BackpressureStrategy]

              

              click digitalkin.models.core.job_manager_models.BackpressureStrategy href "" "digitalkin.models.core.job_manager_models.BackpressureStrategy"
            

Backpressure strategy for module output queue writes.

JobManagerMode ¤

              flowchart TD
              digitalkin.models.core.job_manager_models.JobManagerMode[JobManagerMode]

              

              click digitalkin.models.core.job_manager_models.JobManagerMode href "" "digitalkin.models.core.job_manager_models.JobManagerMode"
            

Job manager mode.

Methods:

  • __str__

    Get the string representation of the job manager mode.

  • get_manager_class

    Get the job manager class based on the mode.

__str__ ¤
__str__() -> str

Get the string representation of the job manager mode.

Returns:

  • str ( str ) –

    job manager mode name.

get_manager_class ¤
get_manager_class() -> type[BaseJobManager]

Get the job manager class based on the mode.

Returns:

task_monitor ¤

Task monitoring models for signaling messages.

Classes:

CancellationReason ¤

              flowchart TD
              digitalkin.models.core.task_monitor.CancellationReason[CancellationReason]

              

              click digitalkin.models.core.task_monitor.CancellationReason href "" "digitalkin.models.core.task_monitor.CancellationReason"
            

Reason for task termination.

SignalMessage ¤

              flowchart TD
              digitalkin.models.core.task_monitor.SignalMessage[SignalMessage]

              

              click digitalkin.models.core.task_monitor.SignalMessage href "" "digitalkin.models.core.task_monitor.SignalMessage"
            

Signal message model for task monitoring.

SignalType ¤

              flowchart TD
              digitalkin.models.core.task_monitor.SignalType[SignalType]

              

              click digitalkin.models.core.task_monitor.SignalType href "" "digitalkin.models.core.task_monitor.SignalType"
            

Signal type enumeration.

events ¤

Agent run event models for DigitalKin.

This module provides framework-agnostic event models for agent runs. These models can be used as a common interface across different AI frameworks.

Modules:

  • agent_events

    Framework-agnostic agent run event models.

Classes:

AgentRunEvent ¤


              flowchart TD
              digitalkin.models.events.AgentRunEvent[AgentRunEvent]

              

              click digitalkin.models.events.AgentRunEvent href "" "digitalkin.models.events.AgentRunEvent"
            

Agent run event types.

BaseAgentRunEvent ¤


              flowchart TD
              digitalkin.models.events.BaseAgentRunEvent[BaseAgentRunEvent]

              

              click digitalkin.models.events.BaseAgentRunEvent href "" "digitalkin.models.events.BaseAgentRunEvent"
            

Base class for all agent run events.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

CustomEvent ¤


              flowchart TD
              digitalkin.models.events.CustomEvent[CustomEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.CustomEvent
                


              click digitalkin.models.events.CustomEvent href "" "digitalkin.models.events.CustomEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted for application-defined custom events.

Carries an application-specific name that discriminates the custom event subtype and a free-form value payload for metadata transfer.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningCompletedEvent ¤


              flowchart TD
              digitalkin.models.events.ReasoningCompletedEvent[ReasoningCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningCompletedEvent
                


              click digitalkin.models.events.ReasoningCompletedEvent href "" "digitalkin.models.events.ReasoningCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a reasoning phase completes.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningContentDeltaEvent ¤


              flowchart TD
              digitalkin.models.events.ReasoningContentDeltaEvent[ReasoningContentDeltaEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningContentDeltaEvent
                


              click digitalkin.models.events.ReasoningContentDeltaEvent href "" "digitalkin.models.events.ReasoningContentDeltaEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted during extended thinking/reasoning phases.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningStartedEvent ¤


              flowchart TD
              digitalkin.models.events.ReasoningStartedEvent[ReasoningStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningStartedEvent
                


              click digitalkin.models.events.ReasoningStartedEvent href "" "digitalkin.models.events.ReasoningStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a reasoning phase starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningStepEvent ¤


              flowchart TD
              digitalkin.models.events.ReasoningStepEvent[ReasoningStepEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningStepEvent
                


              click digitalkin.models.events.ReasoningStepEvent href "" "digitalkin.models.events.ReasoningStepEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted for intermediate reasoning steps.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunCompletedEvent ¤


              flowchart TD
              digitalkin.models.events.RunCompletedEvent[RunCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunCompletedEvent
                


              click digitalkin.models.events.RunCompletedEvent href "" "digitalkin.models.events.RunCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run completes successfully.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunContentEvent ¤


              flowchart TD
              digitalkin.models.events.RunContentEvent[RunContentEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunContentEvent
                


              click digitalkin.models.events.RunContentEvent href "" "digitalkin.models.events.RunContentEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when the agent produces content (text, reasoning, etc.).

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunErrorEvent ¤


              flowchart TD
              digitalkin.models.events.RunErrorEvent[RunErrorEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunErrorEvent
                


              click digitalkin.models.events.RunErrorEvent href "" "digitalkin.models.events.RunErrorEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run encounters an error.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunStartedEvent ¤


              flowchart TD
              digitalkin.models.events.RunStartedEvent[RunStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunStartedEvent
                


              click digitalkin.models.events.RunStartedEvent href "" "digitalkin.models.events.RunStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

TextMessageCompletedEvent ¤


              flowchart TD
              digitalkin.models.events.TextMessageCompletedEvent[TextMessageCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.TextMessageCompletedEvent
                


              click digitalkin.models.events.TextMessageCompletedEvent href "" "digitalkin.models.events.TextMessageCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a text message sequence ends.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

TextMessageStartedEvent ¤


              flowchart TD
              digitalkin.models.events.TextMessageStartedEvent[TextMessageStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.TextMessageStartedEvent
                


              click digitalkin.models.events.TextMessageStartedEvent href "" "digitalkin.models.events.TextMessageStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a new text message sequence begins.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallCompletedEvent ¤


              flowchart TD
              digitalkin.models.events.ToolCallCompletedEvent[ToolCallCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ToolCallCompletedEvent
                


              click digitalkin.models.events.ToolCallCompletedEvent href "" "digitalkin.models.events.ToolCallCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call completes successfully.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallErrorEvent ¤


              flowchart TD
              digitalkin.models.events.ToolCallErrorEvent[ToolCallErrorEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ToolCallErrorEvent
                


              click digitalkin.models.events.ToolCallErrorEvent href "" "digitalkin.models.events.ToolCallErrorEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call encounters an error.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallStartedEvent ¤


              flowchart TD
              digitalkin.models.events.ToolCallStartedEvent[ToolCallStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ToolCallStartedEvent
                


              click digitalkin.models.events.ToolCallStartedEvent href "" "digitalkin.models.events.ToolCallStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolInfo ¤


              flowchart TD
              digitalkin.models.events.ToolInfo[ToolInfo]

              

              click digitalkin.models.events.ToolInfo href "" "digitalkin.models.events.ToolInfo"
            

Information about a tool call.

agent_events ¤

Framework-agnostic agent run event models.

These models define a common interface for agent execution events that can be used across different AI frameworks (Agno, LangChain, custom agents, etc.).

Classes:

AgentRunEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.AgentRunEvent[AgentRunEvent]

              

              click digitalkin.models.events.agent_events.AgentRunEvent href "" "digitalkin.models.events.agent_events.AgentRunEvent"
            

Agent run event types.

BaseAgentRunEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

              

              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Base class for all agent run events.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

CustomEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.CustomEvent[CustomEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.CustomEvent
                


              click digitalkin.models.events.agent_events.CustomEvent href "" "digitalkin.models.events.agent_events.CustomEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted for application-defined custom events.

Carries an application-specific name that discriminates the custom event subtype and a free-form value payload for metadata transfer.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningCompletedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ReasoningCompletedEvent[ReasoningCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningCompletedEvent
                


              click digitalkin.models.events.agent_events.ReasoningCompletedEvent href "" "digitalkin.models.events.agent_events.ReasoningCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a reasoning phase completes.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningContentDeltaEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ReasoningContentDeltaEvent[ReasoningContentDeltaEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningContentDeltaEvent
                


              click digitalkin.models.events.agent_events.ReasoningContentDeltaEvent href "" "digitalkin.models.events.agent_events.ReasoningContentDeltaEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted during extended thinking/reasoning phases.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningStartedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ReasoningStartedEvent[ReasoningStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningStartedEvent
                


              click digitalkin.models.events.agent_events.ReasoningStartedEvent href "" "digitalkin.models.events.agent_events.ReasoningStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a reasoning phase starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ReasoningStepEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ReasoningStepEvent[ReasoningStepEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningStepEvent
                


              click digitalkin.models.events.agent_events.ReasoningStepEvent href "" "digitalkin.models.events.agent_events.ReasoningStepEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted for intermediate reasoning steps.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunCompletedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.RunCompletedEvent[RunCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunCompletedEvent
                


              click digitalkin.models.events.agent_events.RunCompletedEvent href "" "digitalkin.models.events.agent_events.RunCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run completes successfully.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunContentEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.RunContentEvent[RunContentEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunContentEvent
                


              click digitalkin.models.events.agent_events.RunContentEvent href "" "digitalkin.models.events.agent_events.RunContentEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when the agent produces content (text, reasoning, etc.).

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunErrorEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.RunErrorEvent[RunErrorEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunErrorEvent
                


              click digitalkin.models.events.agent_events.RunErrorEvent href "" "digitalkin.models.events.agent_events.RunErrorEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run encounters an error.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

RunStartedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.RunStartedEvent[RunStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunStartedEvent
                


              click digitalkin.models.events.agent_events.RunStartedEvent href "" "digitalkin.models.events.agent_events.RunStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when an agent run starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

TextMessageCompletedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.TextMessageCompletedEvent[TextMessageCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.TextMessageCompletedEvent
                


              click digitalkin.models.events.agent_events.TextMessageCompletedEvent href "" "digitalkin.models.events.agent_events.TextMessageCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a text message sequence ends.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

TextMessageStartedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.TextMessageStartedEvent[TextMessageStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.TextMessageStartedEvent
                


              click digitalkin.models.events.agent_events.TextMessageStartedEvent href "" "digitalkin.models.events.agent_events.TextMessageStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a new text message sequence begins.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallCompletedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ToolCallCompletedEvent[ToolCallCompletedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ToolCallCompletedEvent
                


              click digitalkin.models.events.agent_events.ToolCallCompletedEvent href "" "digitalkin.models.events.agent_events.ToolCallCompletedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call completes successfully.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallErrorEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ToolCallErrorEvent[ToolCallErrorEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ToolCallErrorEvent
                


              click digitalkin.models.events.agent_events.ToolCallErrorEvent href "" "digitalkin.models.events.agent_events.ToolCallErrorEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call encounters an error.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolCallStartedEvent ¤

              flowchart TD
              digitalkin.models.events.agent_events.ToolCallStartedEvent[ToolCallStartedEvent]
              digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]

                              digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ToolCallStartedEvent
                


              click digitalkin.models.events.agent_events.ToolCallStartedEvent href "" "digitalkin.models.events.agent_events.ToolCallStartedEvent"
              click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
            

Event emitted when a tool call starts.

Classes:

  • Config

    Pydantic configuration.

Config ¤

Pydantic configuration.

ToolInfo ¤

              flowchart TD
              digitalkin.models.events.agent_events.ToolInfo[ToolInfo]

              

              click digitalkin.models.events.agent_events.ToolInfo href "" "digitalkin.models.events.agent_events.ToolInfo"
            

Information about a tool call.

grpc_servers ¤

Base gRPC server and client models.

Modules:

  • models

    Data models for gRPC server configurations.

  • types

    Type definitions for gRPC utilities.

models ¤

Data models for gRPC server configurations.

Classes:

ChannelConfig ¤

              flowchart TD
              digitalkin.models.grpc_servers.models.ChannelConfig[ChannelConfig]

              

              click digitalkin.models.grpc_servers.models.ChannelConfig href "" "digitalkin.models.grpc_servers.models.ChannelConfig"
            

Base configuration for gRPC channels.

Attributes:

  • host (str) –

    Host address

  • port (int) –

    Port to listen on

  • mode (ControlFlow) –

    communication operation mode (sync/async)

  • security (SecurityMode) –

    Security mode (secure/insecure)

  • credentials (SecurityMode) –

    Client credentials for secure mode

Methods:

address property ¤
address: str

Get the server address.

Returns:

  • str

    The formatted address string

validate_port classmethod ¤
validate_port(v: int) -> int

Validate that the port is in a valid range.

Parameters:

  • v ¤ (int) –

    Port number to validate

Returns:

  • int

    The validated port number

Raises:

ClientConfig ¤

              flowchart TD
              digitalkin.models.grpc_servers.models.ClientConfig[ClientConfig]
              digitalkin.models.grpc_servers.models.ChannelConfig[ChannelConfig]

                              digitalkin.models.grpc_servers.models.ChannelConfig --> digitalkin.models.grpc_servers.models.ClientConfig
                


              click digitalkin.models.grpc_servers.models.ClientConfig href "" "digitalkin.models.grpc_servers.models.ClientConfig"
              click digitalkin.models.grpc_servers.models.ChannelConfig href "" "digitalkin.models.grpc_servers.models.ChannelConfig"
            

Base configuration for gRPC clients.

Attributes:

  • host (str) –

    Host address to bind the client to

  • port (int) –

    Port to listen on

  • mode (ControlFlow) –

    Client operation mode (sync/async)

  • security (SecurityMode) –

    Security mode (secure/insecure)

  • credentials (ClientCredentials | None) –

    Client credentials for secure mode

  • channel_options (list[tuple[str, Any]]) –

    Additional channel options

  • retry_policy (RetryPolicy) –

    Retry policy for failed RPCs

  • compression (GrpcCompression) –

    gRPC compression algorithm for channel-level compression

Methods:

address property ¤
address: str

Get the server address.

Returns:

  • str

    The formatted address string

grpc_options property ¤
grpc_options: list[tuple[str, Any]]

Get channel options with retry policy service config.

Returns:

validate_credentials classmethod ¤
validate_credentials(
    v: ClientCredentials | None, info: ValidationInfo
) -> ClientCredentials | None

Validate that credentials are provided when in secure mode.

Parameters:

  • v ¤ (ClientCredentials | None) –

    The credentials value

  • info ¤ (ValidationInfo) –

    ValidationInfo containing other field values

Returns:

Raises:

validate_port classmethod ¤
validate_port(v: int) -> int

Validate that the port is in a valid range.

Parameters:

  • v ¤ (int) –

    Port number to validate

Returns:

  • int

    The validated port number

Raises:

ClientCredentials ¤

              flowchart TD
              digitalkin.models.grpc_servers.models.ClientCredentials[ClientCredentials]

              

              click digitalkin.models.grpc_servers.models.ClientCredentials href "" "digitalkin.models.grpc_servers.models.ClientCredentials"
            

Model for client credentials in secure mode.

Attributes:

  • root_cert_path (Path) –

    path to the root certificate

  • client_key_path (Path | None) –

    Path to the client private key

  • client_cert_path (Path | None) –

    Path to the client certificate

Methods:

check_path_exists classmethod ¤
check_path_exists(v: Path | None) -> Path | None

Validate that the file path exists.

Parameters:

  • v ¤ (Path | None) –

    Path to validate

Returns:

  • Path | None

    The validated path

Raises:

GrpcCompression ¤

              flowchart TD
              digitalkin.models.grpc_servers.models.GrpcCompression[GrpcCompression]

              

              click digitalkin.models.grpc_servers.models.GrpcCompression href "" "digitalkin.models.grpc_servers.models.GrpcCompression"
            

gRPC compression algorithm.

Attributes:

  • NONE

    No compression

  • GZIP

    Gzip compression

  • DEFLATE

    Deflate compression

Methods:

  • to_grpc

    Convert to grpc.Compression enum.

to_grpc ¤
to_grpc() -> Compression

Convert to grpc.Compression enum.

Returns:

  • Compression

    The corresponding grpc.Compression value.

RetryPolicy ¤

              flowchart TD
              digitalkin.models.grpc_servers.models.RetryPolicy[RetryPolicy]

              

              click digitalkin.models.grpc_servers.models.RetryPolicy href "" "digitalkin.models.grpc_servers.models.RetryPolicy"
            

gRPC retry policy configuration for resilient connections.

Attributes:

  • max_attempts (int) –

    Maximum retry attempts including the original call

  • initial_backoff (str) –

    Initial backoff duration (e.g., "0.1s")

  • max_backoff (str) –

    Maximum backoff duration (e.g., "10s")

  • backoff_multiplier (float) –

    Multiplier for exponential backoff

  • retryable_status_codes (list[str]) –

    gRPC status codes that trigger retry

Methods:

to_service_config_json ¤
to_service_config_json() -> str

Serialize to gRPC service config JSON string.

Returns:

  • str

    JSON string for grpc.service_config channel option.

types ¤

Type definitions for gRPC utilities.

Classes:

ServiceDescriptor ¤

              flowchart TD
              digitalkin.models.grpc_servers.types.ServiceDescriptor[ServiceDescriptor]

              

              click digitalkin.models.grpc_servers.types.ServiceDescriptor href "" "digitalkin.models.grpc_servers.types.ServiceDescriptor"
            

Protocol for gRPC service descriptors.

ServiceObject ¤

              flowchart TD
              digitalkin.models.grpc_servers.types.ServiceObject[ServiceObject]

              

              click digitalkin.models.grpc_servers.types.ServiceObject href "" "digitalkin.models.grpc_servers.types.ServiceObject"
            

Protocol for individual services in a gRPC descriptor.

module ¤

This module contains the models for the modules.

Modules:

  • ag_ui

    Output model for the Template module.

  • base_types

    Base types for module models.

  • module

    Module model.

  • module_context

    Define the module context used in the triggers.

  • module_types

    Types for module models - backward compatibility re-exports.

  • request_metadata

    Immutable container for gRPC request metadata (headers).

  • select_schema

    SelectSchema for trigger selection UI generation.

  • setup_types

    Setup model types with dynamic schema resolution and tool reference support.

  • tool_cache

    Tool cache for resolved tool references.

  • tool_reference

    Tool reference types for module configuration.

  • utility

    Utility protocols for SDK-provided functionality.

Classes:

  • DataModel

    Base definition of input/output model showing mandatory root fields.

  • DataTrigger

    Defines the root input/output model exposing the protocol.

  • EndOfStreamOutput

    Signal that the stream has ended.

  • ModuleContext

    ModuleContext provides a container for strategies and resources used by a module.

  • ModuleStartInfoOutput

    Output sent when module starts with execution context.

  • RequestMetadata

    Immutable container for gRPC request metadata (headers).

  • SelectSchema

    Base class for generating trigger selection schema.

  • SetupModel

    Base setup model with dynamic schema and tool cache support.

  • ToolCache

    Registry cache storing resolved tool references by setup field name.

  • ToolDefinition

    Complete definition of an LLM tool with resolved JSON Schema parameters.

  • ToolModuleInfo

    Module info for tool modules.

  • ToolReference

    Tool selection containing setup IDs and trigger filters.

  • ToolSelection

    Single tool selection with trigger filtering.

  • UtilityProtocol

    Base class for SDK-provided utility protocols.

  • UtilityRegistry

    Registry for SDK-provided built-in triggers.

Functions:

DataModel ¤


              flowchart TD
              digitalkin.models.module.DataModel[DataModel]

              

              click digitalkin.models.module.DataModel href "" "digitalkin.models.module.DataModel"
            

Base definition of input/output model showing mandatory root fields.

The Model define the Module Input/output, usually referring to multiple input/output type defined by an union.

Example

class ModuleInput(DataModel): root: FileInput | MessageInput

DataTrigger ¤


              flowchart TD
              digitalkin.models.module.DataTrigger[DataTrigger]

              

              click digitalkin.models.module.DataTrigger href "" "digitalkin.models.module.DataTrigger"
            

Defines the root input/output model exposing the protocol.

The mandatory protocol is important to define the module beahvior following the user or agent input/output.

Example

class MyInput(DataModel): root: DataTrigger user_define_data: Any

Usage¤

my_input = MyInput(root=DataTrigger(protocol="message")) print(my_input.root.protocol) # Output: message

EndOfStreamOutput ¤


              flowchart TD
              digitalkin.models.module.EndOfStreamOutput[EndOfStreamOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.EndOfStreamOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.EndOfStreamOutput href "" "digitalkin.models.module.EndOfStreamOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Signal that the stream has ended.

ModuleContext ¤

ModuleContext provides a container for strategies and resources used by a module.

This context object is designed to be passed to module components, providing them with access to shared strategies and resources. Additional attributes may be set dynamically.

Parameters:

Methods:

cleanup async ¤
cleanup() -> None

Close all service strategies and release their resources.

create_openai_style_tools ¤
create_openai_style_tools(setup_id: str) -> list[dict[str, Any]]

Create OpenAI-style function calling schemas for a tool module.

Uses tool cache (fast path) with registry fallback. Returns one schema per ToolDefinition (protocol) in the module. Includes cost information both in the description and as separate metadata.

Parameters:

  • setup_id ¤
    (str) –

    Setup ID to look up (checks cache first, then registry).

Returns:

  • list[dict[str, Any]]

    List of OpenAI-style tool schemas, one per protocol. Empty if not found.

create_tool_functions ¤
create_tool_functions(
    slug: str,
) -> list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]

Create tool functions for all protocols in a tool setup.

Returns an async generator per ToolDefinition that calls the remote tool module via gRPC with the protocol auto-injected.

This method only uses the tool cache (no registry fallback). Use this in sync contexts like init methods.

Parameters:

  • slug ¤
    (str) –

    Setup ID to look up in cache.

Returns:

get_module_schemas_by_id async ¤
get_module_schemas_by_id(
    module_id: str, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas by ID, discovering address/port from registry.

Parameters:

  • module_id ¤
    (str) –

    Module identifier to look up in registry.

  • llm_format ¤
    (bool, default: False ) –

    If True, return LLM-optimized schema format.

Returns:

  • dict[str, dict]

    Dictionary containing schemas: {"input": ..., "output": ..., "setup": ..., "secret": ...}

ModuleStartInfoOutput ¤


              flowchart TD
              digitalkin.models.module.ModuleStartInfoOutput[ModuleStartInfoOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.ModuleStartInfoOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.ModuleStartInfoOutput href "" "digitalkin.models.module.ModuleStartInfoOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Output sent when module starts with execution context.

This protocol is sent as the first message when a module starts, providing the client with essential execution context information.

RequestMetadata ¤

RequestMetadata(raw: dict[str, str] | None = None)

Immutable container for gRPC request metadata (headers).

Provides typed access to common auth headers and raw access to all metadata. Filters out gRPC-reserved keys (prefixed with grpc-).

Example::

metadata = RequestMetadata({"authorization": "Bearer eyJ...", "x-tenant-id": "t-123"})
token = metadata.bearer_token  # "eyJ..."
tenant = metadata.get("x-tenant-id")  # "t-123"

Parameters:

  • raw ¤
    (dict[str, str] | None, default: None ) –

    Dictionary of metadata key-value pairs. Keys prefixed with grpc- are filtered out.

Methods:

  • __bool__

    Return True if metadata is non-empty.

  • __contains__

    Check if a metadata key exists.

  • __getitem__

    Get a metadata value by key.

  • __repr__

    Return a string representation (sensitive values masked).

  • get

    Get any metadata value by key.

  • to_dict

    Return a copy of the raw metadata dictionary.

  • to_grpc_metadata

    Convert to gRPC metadata format for forwarding.

Attributes:

  • api_key (str | None) –

    Get the x-api-key header value.

  • authorization (str | None) –

    Get the Authorization header value (e.g., Bearer <token>).

  • bearer_token (str | None) –

    Extract the bearer token from the Authorization header.

api_key property ¤
api_key: str | None

Get the x-api-key header value.

authorization property ¤
authorization: str | None

Get the Authorization header value (e.g., Bearer <token>).

bearer_token property ¤
bearer_token: str | None

Extract the bearer token from the Authorization header.

Returns:

  • str | None

    The token string if the Authorization header starts with Bearer, otherwise None.

__bool__ ¤
__bool__() -> bool

Return True if metadata is non-empty.

__contains__ ¤
__contains__(key: object) -> bool

Check if a metadata key exists.

Returns:

  • bool

    True if key is present.

__getitem__ ¤
__getitem__(key: str) -> str

Get a metadata value by key.

Parameters:

  • key ¤
    (str) –

    Metadata key.

Returns:

  • str

    The metadata value.

Raises:

__repr__ ¤
__repr__() -> str

Return a string representation (sensitive values masked).

get ¤
get(key: str, default: str | None = None) -> str | None

Get any metadata value by key.

Parameters:

  • key ¤
    (str) –

    Metadata key.

  • default ¤
    (str | None, default: None ) –

    Default value if key is not found.

Returns:

  • str | None

    The metadata value or default.

to_dict ¤
to_dict() -> dict[str, str]

Return a copy of the raw metadata dictionary.

to_grpc_metadata ¤
to_grpc_metadata() -> list[tuple[str, str]]

Convert to gRPC metadata format for forwarding.

Returns:

  • list[tuple[str, str]]

    List of (key, value) tuples suitable for gRPC metadata= parameter.

SelectSchema ¤


              flowchart TD
              digitalkin.models.module.SelectSchema[SelectSchema]

              

              click digitalkin.models.module.SelectSchema href "" "digitalkin.models.module.SelectSchema"
            

Base class for generating trigger selection schema.

Subclass and add boolean fields to customize the selection UI. If no fields are defined, schema is auto-generated from registered protocols. Set select_format = None in your module to disable.

Example

class MySelectSchema(SelectSchema): message: bool = Field(default=True, title="Message", description="Process messages") file: bool = Field(default=False, title="File", description="Process files")

Methods:

  • build

    Build the select schema.

build classmethod ¤
build(protocols_info: dict[str, str]) -> dict[str, Any] | None

Build the select schema.

If the subclass has user-defined fields, uses those. Otherwise, auto-generates from protocols_info.

Parameters:

  • protocols_info ¤
    (dict[str, str]) –

    Dict mapping protocol name to description.

Returns:

  • dict[str, Any] | None

    Dict with json_schema and ui_schema keys, or None to exclude.

SetupModel ¤


              flowchart TD
              digitalkin.models.module.SetupModel[SetupModel]

              

              click digitalkin.models.module.SetupModel href "" "digitalkin.models.module.SetupModel"
            

Base setup model with dynamic schema and tool cache support.

Methods:

  • build_tool_cache

    Build tool cache, resolving uncached tools via registry.

  • get_clean_model

    Build filtered model based on json_schema_extra metadata.

build_tool_cache async ¤
build_tool_cache(
    registry: RegistryStrategy | None = None,
    communication: CommunicationStrategy | None = None,
) -> ToolCache

Build tool cache, resolving uncached tools via registry.

Walks ToolReference fields recursively. For each selected tool, checks resolved_tools first (cache). If missing and registry is available, resolves via gRPC and populates the cache.

Parameters:

  • registry ¤
    (RegistryStrategy | None, default: None ) –

    Registry service for resolving uncached tools.

  • communication ¤
    (CommunicationStrategy | None, default: None ) –

    Communication service for module schemas.

Returns:

  • ToolCache

    ToolCache with resolved tool entries.

get_clean_model async classmethod ¤
get_clean_model(
    *, config_fields: bool, hidden_fields: bool, force: bool = False
) -> type[SetupModelT]

Build filtered model based on json_schema_extra metadata.

Parameters:

  • config_fields ¤
    (bool) –

    Include fields with json_schema_extra["config"] = True.

  • hidden_fields ¤
    (bool) –

    Include fields with json_schema_extra["ui:widget"] = "hidden".

  • force ¤
    (bool, default: False ) –

    Refresh dynamic schema fields by calling providers.

Returns:

  • type[SetupModelT]

    New BaseModel subclass with filtered fields.

ToolCache ¤


              flowchart TD
              digitalkin.models.module.ToolCache[ToolCache]

              

              click digitalkin.models.module.ToolCache href "" "digitalkin.models.module.ToolCache"
            

Registry cache storing resolved tool references by setup field name.

Methods:

  • add

    Add a tool to the cache.

  • clear

    Clear all cache entries.

  • get

    Get a tool from cache, optionally querying registry on miss.

  • list_tools

    List all cached tool names.

add ¤

Add a tool to the cache.

Parameters:

clear ¤
clear() -> None

Clear all cache entries.

get ¤
get(setup_id: str) -> ToolModuleInfo | None

Get a tool from cache, optionally querying registry on miss.

Parameters:

  • setup_id ¤
    (str) –

    Field name to look up.

Returns:

list_tools ¤
list_tools() -> list[str]

List all cached tool names.

Returns:

  • list[str]

    List of setup field names in cache.

ToolDefinition ¤


              flowchart TD
              digitalkin.models.module.ToolDefinition[ToolDefinition]

              

              click digitalkin.models.module.ToolDefinition href "" "digitalkin.models.module.ToolDefinition"
            

Complete definition of an LLM tool with resolved JSON Schema parameters.

Attributes:

  • name (str) –

    Tool name (from protocol const or trigger class name).

  • description (str) –

    Tool description (from trigger docstring).

  • parameters_schema (dict[str, Any]) –

    JSON Schema object describing the tool's parameters.

parameter_count property ¤
parameter_count: int

Return the number of parameters in the schema.

parameter_names property ¤
parameter_names: set[str]

Return the set of parameter names from the schema.

ToolModuleInfo ¤


              flowchart TD
              digitalkin.models.module.ToolModuleInfo[ToolModuleInfo]
              digitalkin.models.services.registry.ModuleInfo[ModuleInfo]

                              digitalkin.models.services.registry.ModuleInfo --> digitalkin.models.module.ToolModuleInfo
                


              click digitalkin.models.module.ToolModuleInfo href "" "digitalkin.models.module.ToolModuleInfo"
              click digitalkin.models.services.registry.ModuleInfo href "" "digitalkin.models.services.registry.ModuleInfo"
            

Module info for tool modules.

Attributes:

  • slug (str) –

    Slugified tool name for cache keys and function naming.

slug property ¤
slug: str

Slugified tool name for cache keys and function naming.

ToolReference ¤


              flowchart TD
              digitalkin.models.module.ToolReference[ToolReference]

              

              click digitalkin.models.module.ToolReference href "" "digitalkin.models.module.ToolReference"
            

Tool selection containing setup IDs and trigger filters.

Methods:

  • resolve

    Resolve selected tools using the registry.

resolve async ¤

Resolve selected tools using the registry.

Each tool resolution is bounded by DIGITALKIN_TOOL_RESOLVE_TIMEOUT (default 10s).

Parameters:

Returns:

  • list[ToolModuleInfo]

    List of ToolModuleInfo for resolved tools, filtered by enabled triggers.

ToolSelection ¤


              flowchart TD
              digitalkin.models.module.ToolSelection[ToolSelection]

              

              click digitalkin.models.module.ToolSelection href "" "digitalkin.models.module.ToolSelection"
            

Single tool selection with trigger filtering.

UtilityProtocol ¤


              flowchart TD
              digitalkin.models.module.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.UtilityProtocol
                


              click digitalkin.models.module.UtilityProtocol href "" "digitalkin.models.module.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Base class for SDK-provided utility protocols.

All SDK utility protocols inherit from this class to enable: - Easy identification of SDK vs user-defined protocols - Auto-injection capability - Consistent behavior across the SDK

UtilityRegistry ¤

Registry for SDK-provided built-in triggers.

Example

builtin_triggers = UtilityRegistry.get_builtin_triggers()

Methods:

get_builtin_triggers classmethod ¤
get_builtin_triggers() -> tuple

Get all SDK-provided built-in trigger handlers.

Uses lazy loading to avoid circular imports with the modules package.

Returns:

  • tuple

    Tuple of TriggerHandler subclasses for built-in functionality.

tool_reference_input ¤

tool_reference_input(
    setup_ids: list[str] | None = None,
    module_ids: list[str] | None = None,
    tag_ids: list[str] | None = None,
    categories: list[str] | None = None,
    max_tools: int = 0,
    min_tools: int = 0,
) -> type[ToolReference]

Create ToolReferenceInput type with schema options and validation.

Parameters:

  • setup_ids ¤
    (list[str] | None, default: None ) –

    Setup IDs for the user to choose from.

  • module_ids ¤
    (list[str] | None, default: None ) –

    Module IDs for the user to choose from.

  • tag_ids ¤
    (list[str] | None, default: None ) –

    Tag IDs for the user to choose from.

  • categories ¤
    (list[str] | None, default: None ) –

    Categories for the user to choose from.

  • max_tools ¤
    (int, default: 0 ) –

    Maximum tools allowed. 0 for unlimited.

  • min_tools ¤
    (int, default: 0 ) –

    Minimum tools required. 0 for no minimum.

Returns:

ag_ui ¤

Output model for the Template module.

Classes:

AgUiActivityDeltaOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput[AgUiActivityDeltaOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput href "" "digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ActivityDelta event - JSON Patch delta for an activity message.

AgUiActivitySnapshotOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput[AgUiActivitySnapshotOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput href "" "digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ActivitySnapshot event - full activity message snapshot.

AgUiCustomEventOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiCustomEventOutput[AgUiCustomEventOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiCustomEventOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiCustomEventOutput href "" "digitalkin.models.module.ag_ui.AgUiCustomEventOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI CustomEvent event - carries an application-defined custom event.

AgUiDataTrigger ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                


              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

DataTrigger subclass that serializes wrapper fields as camelCase.

AG-UI events must be serialized with camelCase field names. Since the SDK calls model_dump(mode="json") without by_alias=True, we define camelCase aliases here and activate them via TemplateOutput.model_dump.

AgUiMessagesSnapshotOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput[AgUiMessagesSnapshotOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput href "" "digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI MessagesSnapshot event - full conversation messages snapshot.

AgUiOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiOutput[AgUiOutput]
              digitalkin.models.module.base_types.DataModel[DataModel]

                              digitalkin.models.module.base_types.DataModel --> digitalkin.models.module.ag_ui.AgUiOutput
                


              click digitalkin.models.module.ag_ui.AgUiOutput href "" "digitalkin.models.module.ag_ui.AgUiOutput"
              click digitalkin.models.module.base_types.DataModel href "" "digitalkin.models.module.base_types.DataModel"
            

Output model for the Template module with discriminated union.

Methods:

  • model_dump

    Serialize with camelCase aliases and exclude None fields by default.

model_dump ¤
model_dump(**kwargs: object) -> dict[str, object]

Serialize with camelCase aliases and exclude None fields by default.

Returns:

  • dict[str, object]

    Serialized model dictionary with camelCase keys and no null values.

AgUiRawEventOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiRawEventOutput[AgUiRawEventOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRawEventOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiRawEventOutput href "" "digitalkin.models.module.ag_ui.AgUiRawEventOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI RawEvent event - passes through a raw/untyped event payload.

AgUiReasoningEncryptedValueOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput[AgUiReasoningEncryptedValueOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningEncryptedValue event - carries an encrypted reasoning value.

AgUiReasoningEndOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningEndOutput[AgUiReasoningEndOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningEndOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningEndOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningEndOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningEnd event - signals end of a reasoning phase.

AgUiReasoningMessageChunkOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput[AgUiReasoningMessageChunkOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningMessageChunk event - aggregated reasoning message chunk.

AgUiReasoningMessageContentOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput[AgUiReasoningMessageContentOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningMessageContent event - carries a reasoning content delta.

AgUiReasoningMessageEndOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput[AgUiReasoningMessageEndOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningMessageEnd event - signals end of a reasoning message.

AgUiReasoningMessageStartOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput[AgUiReasoningMessageStartOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningMessageStart event - signals start of a reasoning message.

AgUiReasoningStartOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiReasoningStartOutput[AgUiReasoningStartOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningStartOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiReasoningStartOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningStartOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ReasoningStart event - signals start of a reasoning phase.

AgUiRunErrorOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiRunErrorOutput[AgUiRunErrorOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRunErrorOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiRunErrorOutput href "" "digitalkin.models.module.ag_ui.AgUiRunErrorOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI RunError event - signals that a run encountered an error.

AgUiRunFinishedOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiRunFinishedOutput[AgUiRunFinishedOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRunFinishedOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiRunFinishedOutput href "" "digitalkin.models.module.ag_ui.AgUiRunFinishedOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI RunFinished event - signals that an agent run has completed.

AgUiRunStartedOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiRunStartedOutput[AgUiRunStartedOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRunStartedOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiRunStartedOutput href "" "digitalkin.models.module.ag_ui.AgUiRunStartedOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI RunStarted event - signals that an agent run has begun.

AgUiStateDeltaOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiStateDeltaOutput[AgUiStateDeltaOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStateDeltaOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiStateDeltaOutput href "" "digitalkin.models.module.ag_ui.AgUiStateDeltaOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI StateDelta event - JSON Patch (RFC 6902) operations on agent state.

AgUiStateSnapshotOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput[AgUiStateSnapshotOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput href "" "digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI StateSnapshot event - full agent state snapshot.

AgUiStepFinishedOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiStepFinishedOutput[AgUiStepFinishedOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStepFinishedOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiStepFinishedOutput href "" "digitalkin.models.module.ag_ui.AgUiStepFinishedOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI StepFinished event - signals completion of a named agent step.

AgUiStepStartedOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiStepStartedOutput[AgUiStepStartedOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStepStartedOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiStepStartedOutput href "" "digitalkin.models.module.ag_ui.AgUiStepStartedOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI StepStarted event - signals start of a named agent step.

AgUiTextMessageChunkOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput[AgUiTextMessageChunkOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI TextMessageChunk event - aggregated text message chunk.

AgUiTextMessageContentOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput[AgUiTextMessageContentOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI TextMessageContent event - carries a text delta chunk.

AgUiTextMessageEndOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput[AgUiTextMessageEndOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI TextMessageEnd event - signals end of a text message.

AgUiTextMessageStartOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput[AgUiTextMessageStartOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI TextMessageStart event - signals start of a text message.

AgUiThinkingEndOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiThinkingEndOutput[AgUiThinkingEndOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingEndOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiThinkingEndOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingEndOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ThinkingEnd event - signals end of a high-level thinking step.

AgUiThinkingStartOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiThinkingStartOutput[AgUiThinkingStartOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingStartOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiThinkingStartOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingStartOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ThinkingStart event - signals start of a high-level thinking step.

AgUiThinkingTextMessageContentOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput[AgUiThinkingTextMessageContentOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ThinkingTextMessageContent event - carries a thinking text delta chunk.

AgUiThinkingTextMessageEndOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput[AgUiThinkingTextMessageEndOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ThinkingTextMessageEnd event - signals end of internal thinking.

AgUiThinkingTextMessageStartOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput[AgUiThinkingTextMessageStartOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ThinkingTextMessageStart event - signals start of internal thinking.

AgUiToolCallArgsOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput[AgUiToolCallArgsOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ToolCallArgs event - carries streamed tool call arguments delta.

AgUiToolCallChunkOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput[AgUiToolCallChunkOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ToolCallChunk event - aggregated tool call chunk.

AgUiToolCallEndOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiToolCallEndOutput[AgUiToolCallEndOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallEndOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiToolCallEndOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallEndOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ToolCallEnd event - signals end of tool call argument streaming.

AgUiToolCallResultOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiToolCallResultOutput[AgUiToolCallResultOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallResultOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiToolCallResultOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallResultOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ToolCallResult event - carries the result of a completed tool call.

AgUiToolCallStartOutput ¤

              flowchart TD
              digitalkin.models.module.ag_ui.AgUiToolCallStartOutput[AgUiToolCallStartOutput]
              digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallStartOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
                



              click digitalkin.models.module.ag_ui.AgUiToolCallStartOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallStartOutput"
              click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

AG-UI ToolCallStart event - signals start of a tool invocation.

base_types ¤

Base types for module models.

Classes:

  • DataModel

    Base definition of input/output model showing mandatory root fields.

  • DataTrigger

    Defines the root input/output model exposing the protocol.

DataModel ¤

              flowchart TD
              digitalkin.models.module.base_types.DataModel[DataModel]

              

              click digitalkin.models.module.base_types.DataModel href "" "digitalkin.models.module.base_types.DataModel"
            

Base definition of input/output model showing mandatory root fields.

The Model define the Module Input/output, usually referring to multiple input/output type defined by an union.

Example

class ModuleInput(DataModel): root: FileInput | MessageInput

DataTrigger ¤

              flowchart TD
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

              

              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Defines the root input/output model exposing the protocol.

The mandatory protocol is important to define the module beahvior following the user or agent input/output.

Example

class MyInput(DataModel): root: DataTrigger user_define_data: Any

Usage¤

my_input = MyInput(root=DataTrigger(protocol="message")) print(my_input.root.protocol) # Output: message

module ¤

Module model.

Classes:

Module ¤

              flowchart TD
              digitalkin.models.module.module.Module[Module]

              

              click digitalkin.models.module.module.Module href "" "digitalkin.models.module.module.Module"
            

Module model.

ModuleCodeModel ¤

              flowchart TD
              digitalkin.models.module.module.ModuleCodeModel[ModuleCodeModel]

              

              click digitalkin.models.module.module.ModuleCodeModel href "" "digitalkin.models.module.module.ModuleCodeModel"
            

typed error/code model.

ModuleStatus ¤

              flowchart TD
              digitalkin.models.module.module.ModuleStatus[ModuleStatus]

              

              click digitalkin.models.module.module.ModuleStatus href "" "digitalkin.models.module.module.ModuleStatus"
            

Possible module's state.

module_context ¤

Define the module context used in the triggers.

Classes:

  • ModuleContext

    ModuleContext provides a container for strategies and resources used by a module.

  • Session

    Session data container with mandatory setup_id and mission_id.

ModuleContext ¤

ModuleContext provides a container for strategies and resources used by a module.

This context object is designed to be passed to module components, providing them with access to shared strategies and resources. Additional attributes may be set dynamically.

Parameters:

Methods:

cleanup async ¤
cleanup() -> None

Close all service strategies and release their resources.

create_openai_style_tools ¤
create_openai_style_tools(setup_id: str) -> list[dict[str, Any]]

Create OpenAI-style function calling schemas for a tool module.

Uses tool cache (fast path) with registry fallback. Returns one schema per ToolDefinition (protocol) in the module. Includes cost information both in the description and as separate metadata.

Parameters:

  • setup_id ¤ (str) –

    Setup ID to look up (checks cache first, then registry).

Returns:

  • list[dict[str, Any]]

    List of OpenAI-style tool schemas, one per protocol. Empty if not found.

create_tool_functions ¤
create_tool_functions(
    slug: str,
) -> list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]

Create tool functions for all protocols in a tool setup.

Returns an async generator per ToolDefinition that calls the remote tool module via gRPC with the protocol auto-injected.

This method only uses the tool cache (no registry fallback). Use this in sync contexts like init methods.

Parameters:

  • slug ¤ (str) –

    Setup ID to look up in cache.

Returns:

get_module_schemas_by_id async ¤
get_module_schemas_by_id(
    module_id: str, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas by ID, discovering address/port from registry.

Parameters:

  • module_id ¤ (str) –

    Module identifier to look up in registry.

  • llm_format ¤ (bool, default: False ) –

    If True, return LLM-optimized schema format.

Returns:

  • dict[str, dict]

    Dictionary containing schemas: {"input": ..., "output": ..., "setup": ..., "secret": ...}

Session ¤
Session(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    timezone: tzinfo | None = None,
    **kwargs: dict[str, Any],
)

              flowchart TD
              digitalkin.models.module.module_context.Session[Session]

              

              click digitalkin.models.module.module_context.Session href "" "digitalkin.models.module.module_context.Session"
            

Session data container with mandatory setup_id and mission_id.

Raises:

Methods:

  • current_ids

    Return current session ids as a dictionary.

current_ids ¤
current_ids() -> dict[str, str]

Return current session ids as a dictionary.

Returns:

  • dict[str, str]

    A dictionary containing the current session ids.

module_types ¤

Types for module models - backward compatibility re-exports.

This module re-exports types from their new locations for backward compatibility. New code should import directly from the specific modules: - digitalkin.models.module.base_types for DataTrigger, DataModel, TypeVars - digitalkin.models.module.setup_types for SetupModel

Classes:

  • DataModel

    Base definition of input/output model showing mandatory root fields.

  • DataTrigger

    Defines the root input/output model exposing the protocol.

  • SetupModel

    Base setup model with dynamic schema and tool cache support.

DataModel ¤

              flowchart TD
              digitalkin.models.module.module_types.DataModel[DataModel]

              

              click digitalkin.models.module.module_types.DataModel href "" "digitalkin.models.module.module_types.DataModel"
            

Base definition of input/output model showing mandatory root fields.

The Model define the Module Input/output, usually referring to multiple input/output type defined by an union.

Example

class ModuleInput(DataModel): root: FileInput | MessageInput

DataTrigger ¤

              flowchart TD
              digitalkin.models.module.module_types.DataTrigger[DataTrigger]

              

              click digitalkin.models.module.module_types.DataTrigger href "" "digitalkin.models.module.module_types.DataTrigger"
            

Defines the root input/output model exposing the protocol.

The mandatory protocol is important to define the module beahvior following the user or agent input/output.

Example

class MyInput(DataModel): root: DataTrigger user_define_data: Any

Usage¤

my_input = MyInput(root=DataTrigger(protocol="message")) print(my_input.root.protocol) # Output: message

SetupModel ¤

              flowchart TD
              digitalkin.models.module.module_types.SetupModel[SetupModel]

              

              click digitalkin.models.module.module_types.SetupModel href "" "digitalkin.models.module.module_types.SetupModel"
            

Base setup model with dynamic schema and tool cache support.

Methods:

  • build_tool_cache

    Build tool cache, resolving uncached tools via registry.

  • get_clean_model

    Build filtered model based on json_schema_extra metadata.

build_tool_cache async ¤
build_tool_cache(
    registry: RegistryStrategy | None = None,
    communication: CommunicationStrategy | None = None,
) -> ToolCache

Build tool cache, resolving uncached tools via registry.

Walks ToolReference fields recursively. For each selected tool, checks resolved_tools first (cache). If missing and registry is available, resolves via gRPC and populates the cache.

Parameters:

  • registry ¤ (RegistryStrategy | None, default: None ) –

    Registry service for resolving uncached tools.

  • communication ¤ (CommunicationStrategy | None, default: None ) –

    Communication service for module schemas.

Returns:

  • ToolCache

    ToolCache with resolved tool entries.

get_clean_model async classmethod ¤
get_clean_model(
    *, config_fields: bool, hidden_fields: bool, force: bool = False
) -> type[SetupModelT]

Build filtered model based on json_schema_extra metadata.

Parameters:

  • config_fields ¤ (bool) –

    Include fields with json_schema_extra["config"] = True.

  • hidden_fields ¤ (bool) –

    Include fields with json_schema_extra["ui:widget"] = "hidden".

  • force ¤ (bool, default: False ) –

    Refresh dynamic schema fields by calling providers.

Returns:

  • type[SetupModelT]

    New BaseModel subclass with filtered fields.

request_metadata ¤

Immutable container for gRPC request metadata (headers).

Classes:

  • RequestMetadata

    Immutable container for gRPC request metadata (headers).

RequestMetadata ¤
RequestMetadata(raw: dict[str, str] | None = None)

Immutable container for gRPC request metadata (headers).

Provides typed access to common auth headers and raw access to all metadata. Filters out gRPC-reserved keys (prefixed with grpc-).

Example::

metadata = RequestMetadata({"authorization": "Bearer eyJ...", "x-tenant-id": "t-123"})
token = metadata.bearer_token  # "eyJ..."
tenant = metadata.get("x-tenant-id")  # "t-123"

Parameters:

  • raw ¤
    (dict[str, str] | None, default: None ) –

    Dictionary of metadata key-value pairs. Keys prefixed with grpc- are filtered out.

Methods:

  • __bool__

    Return True if metadata is non-empty.

  • __contains__

    Check if a metadata key exists.

  • __getitem__

    Get a metadata value by key.

  • __repr__

    Return a string representation (sensitive values masked).

  • get

    Get any metadata value by key.

  • to_dict

    Return a copy of the raw metadata dictionary.

  • to_grpc_metadata

    Convert to gRPC metadata format for forwarding.

Attributes:

  • api_key (str | None) –

    Get the x-api-key header value.

  • authorization (str | None) –

    Get the Authorization header value (e.g., Bearer <token>).

  • bearer_token (str | None) –

    Extract the bearer token from the Authorization header.

api_key property ¤
api_key: str | None

Get the x-api-key header value.

authorization property ¤
authorization: str | None

Get the Authorization header value (e.g., Bearer <token>).

bearer_token property ¤
bearer_token: str | None

Extract the bearer token from the Authorization header.

Returns:

  • str | None

    The token string if the Authorization header starts with Bearer, otherwise None.

__bool__ ¤
__bool__() -> bool

Return True if metadata is non-empty.

__contains__ ¤
__contains__(key: object) -> bool

Check if a metadata key exists.

Returns:

  • bool

    True if key is present.

__getitem__ ¤
__getitem__(key: str) -> str

Get a metadata value by key.

Parameters:

  • key ¤ (str) –

    Metadata key.

Returns:

  • str

    The metadata value.

Raises:

__repr__ ¤
__repr__() -> str

Return a string representation (sensitive values masked).

get ¤
get(key: str, default: str | None = None) -> str | None

Get any metadata value by key.

Parameters:

  • key ¤ (str) –

    Metadata key.

  • default ¤ (str | None, default: None ) –

    Default value if key is not found.

Returns:

  • str | None

    The metadata value or default.

to_dict ¤
to_dict() -> dict[str, str]

Return a copy of the raw metadata dictionary.

to_grpc_metadata ¤
to_grpc_metadata() -> list[tuple[str, str]]

Convert to gRPC metadata format for forwarding.

Returns:

  • list[tuple[str, str]]

    List of (key, value) tuples suitable for gRPC metadata= parameter.

select_schema ¤

SelectSchema for trigger selection UI generation.

Classes:

  • SelectSchema

    Base class for generating trigger selection schema.

SelectSchema ¤

              flowchart TD
              digitalkin.models.module.select_schema.SelectSchema[SelectSchema]

              

              click digitalkin.models.module.select_schema.SelectSchema href "" "digitalkin.models.module.select_schema.SelectSchema"
            

Base class for generating trigger selection schema.

Subclass and add boolean fields to customize the selection UI. If no fields are defined, schema is auto-generated from registered protocols. Set select_format = None in your module to disable.

Example

class MySelectSchema(SelectSchema): message: bool = Field(default=True, title="Message", description="Process messages") file: bool = Field(default=False, title="File", description="Process files")

Methods:

  • build

    Build the select schema.

build classmethod ¤
build(protocols_info: dict[str, str]) -> dict[str, Any] | None

Build the select schema.

If the subclass has user-defined fields, uses those. Otherwise, auto-generates from protocols_info.

Parameters:

  • protocols_info ¤ (dict[str, str]) –

    Dict mapping protocol name to description.

Returns:

  • dict[str, Any] | None

    Dict with json_schema and ui_schema keys, or None to exclude.

setup_types ¤

Setup model types with dynamic schema resolution and tool reference support.

Classes:

  • SetupModel

    Base setup model with dynamic schema and tool cache support.

SetupModel ¤

              flowchart TD
              digitalkin.models.module.setup_types.SetupModel[SetupModel]

              

              click digitalkin.models.module.setup_types.SetupModel href "" "digitalkin.models.module.setup_types.SetupModel"
            

Base setup model with dynamic schema and tool cache support.

Methods:

  • build_tool_cache

    Build tool cache, resolving uncached tools via registry.

  • get_clean_model

    Build filtered model based on json_schema_extra metadata.

build_tool_cache async ¤
build_tool_cache(
    registry: RegistryStrategy | None = None,
    communication: CommunicationStrategy | None = None,
) -> ToolCache

Build tool cache, resolving uncached tools via registry.

Walks ToolReference fields recursively. For each selected tool, checks resolved_tools first (cache). If missing and registry is available, resolves via gRPC and populates the cache.

Parameters:

  • registry ¤ (RegistryStrategy | None, default: None ) –

    Registry service for resolving uncached tools.

  • communication ¤ (CommunicationStrategy | None, default: None ) –

    Communication service for module schemas.

Returns:

  • ToolCache

    ToolCache with resolved tool entries.

get_clean_model async classmethod ¤
get_clean_model(
    *, config_fields: bool, hidden_fields: bool, force: bool = False
) -> type[SetupModelT]

Build filtered model based on json_schema_extra metadata.

Parameters:

  • config_fields ¤ (bool) –

    Include fields with json_schema_extra["config"] = True.

  • hidden_fields ¤ (bool) –

    Include fields with json_schema_extra["ui:widget"] = "hidden".

  • force ¤ (bool, default: False ) –

    Refresh dynamic schema fields by calling providers.

Returns:

  • type[SetupModelT]

    New BaseModel subclass with filtered fields.

tool_cache ¤

Tool cache for resolved tool references.

Classes:

  • SelectedTool

    Selected tool information.

  • ToolCache

    Registry cache storing resolved tool references by setup field name.

  • ToolDefinition

    Complete definition of an LLM tool with resolved JSON Schema parameters.

  • ToolModuleInfo

    Module info for tool modules.

Functions:

SelectedTool ¤

              flowchart TD
              digitalkin.models.module.tool_cache.SelectedTool[SelectedTool]

              

              click digitalkin.models.module.tool_cache.SelectedTool href "" "digitalkin.models.module.tool_cache.SelectedTool"
            

Selected tool information.

ToolCache ¤

              flowchart TD
              digitalkin.models.module.tool_cache.ToolCache[ToolCache]

              

              click digitalkin.models.module.tool_cache.ToolCache href "" "digitalkin.models.module.tool_cache.ToolCache"
            

Registry cache storing resolved tool references by setup field name.

Methods:

  • add

    Add a tool to the cache.

  • clear

    Clear all cache entries.

  • get

    Get a tool from cache, optionally querying registry on miss.

  • list_tools

    List all cached tool names.

add ¤

Add a tool to the cache.

Parameters:

clear ¤
clear() -> None

Clear all cache entries.

get ¤
get(setup_id: str) -> ToolModuleInfo | None

Get a tool from cache, optionally querying registry on miss.

Parameters:

  • setup_id ¤ (str) –

    Field name to look up.

Returns:

list_tools ¤
list_tools() -> list[str]

List all cached tool names.

Returns:

  • list[str]

    List of setup field names in cache.

ToolDefinition ¤

              flowchart TD
              digitalkin.models.module.tool_cache.ToolDefinition[ToolDefinition]

              

              click digitalkin.models.module.tool_cache.ToolDefinition href "" "digitalkin.models.module.tool_cache.ToolDefinition"
            

Complete definition of an LLM tool with resolved JSON Schema parameters.

Attributes:

  • name (str) –

    Tool name (from protocol const or trigger class name).

  • description (str) –

    Tool description (from trigger docstring).

  • parameters_schema (dict[str, Any]) –

    JSON Schema object describing the tool's parameters.

parameter_count property ¤
parameter_count: int

Return the number of parameters in the schema.

parameter_names property ¤
parameter_names: set[str]

Return the set of parameter names from the schema.

ToolModuleInfo ¤

              flowchart TD
              digitalkin.models.module.tool_cache.ToolModuleInfo[ToolModuleInfo]
              digitalkin.models.services.registry.ModuleInfo[ModuleInfo]

                              digitalkin.models.services.registry.ModuleInfo --> digitalkin.models.module.tool_cache.ToolModuleInfo
                


              click digitalkin.models.module.tool_cache.ToolModuleInfo href "" "digitalkin.models.module.tool_cache.ToolModuleInfo"
              click digitalkin.models.services.registry.ModuleInfo href "" "digitalkin.models.services.registry.ModuleInfo"
            

Module info for tool modules.

Attributes:

  • slug (str) –

    Slugified tool name for cache keys and function naming.

slug property ¤
slug: str

Slugified tool name for cache keys and function naming.

module_info_to_tool_module_info async ¤

Convert ModuleInfo to ToolModuleInfo by fetching schemas via gRPC.

Fetches the module's input schema and extracts tool definitions from the discriminated union structure.

Parameters:

  • module_info ¤
    (ModuleInfo) –

    Module info from registry.

  • setup_id ¤
    (str) –

    Setup ID of the selected tool.

  • tool_name ¤
    (str) –

    Name of the tool.

  • communication ¤
    (CommunicationStrategy) –

    Communication strategy for gRPC calls.

  • llm_format ¤
    (bool, default: True ) –

    Use LLM-friendly schema format.

Returns:

  • ToolModuleInfo

    ToolModuleInfo with tools extracted from input schema.

tool_reference ¤

Tool reference types for module configuration.

Classes:

  • ToolReference

    Tool selection containing setup IDs and trigger filters.

  • ToolSelection

    Single tool selection with trigger filtering.

Functions:

ToolReference ¤

              flowchart TD
              digitalkin.models.module.tool_reference.ToolReference[ToolReference]

              

              click digitalkin.models.module.tool_reference.ToolReference href "" "digitalkin.models.module.tool_reference.ToolReference"
            

Tool selection containing setup IDs and trigger filters.

Methods:

  • resolve

    Resolve selected tools using the registry.

resolve async ¤

Resolve selected tools using the registry.

Each tool resolution is bounded by DIGITALKIN_TOOL_RESOLVE_TIMEOUT (default 10s).

Parameters:

Returns:

  • list[ToolModuleInfo]

    List of ToolModuleInfo for resolved tools, filtered by enabled triggers.

ToolSelection ¤

              flowchart TD
              digitalkin.models.module.tool_reference.ToolSelection[ToolSelection]

              

              click digitalkin.models.module.tool_reference.ToolSelection href "" "digitalkin.models.module.tool_reference.ToolSelection"
            

Single tool selection with trigger filtering.

tool_reference_input ¤
tool_reference_input(
    setup_ids: list[str] | None = None,
    module_ids: list[str] | None = None,
    tag_ids: list[str] | None = None,
    categories: list[str] | None = None,
    max_tools: int = 0,
    min_tools: int = 0,
) -> type[ToolReference]

Create ToolReferenceInput type with schema options and validation.

Parameters:

  • setup_ids ¤
    (list[str] | None, default: None ) –

    Setup IDs for the user to choose from.

  • module_ids ¤
    (list[str] | None, default: None ) –

    Module IDs for the user to choose from.

  • tag_ids ¤
    (list[str] | None, default: None ) –

    Tag IDs for the user to choose from.

  • categories ¤
    (list[str] | None, default: None ) –

    Categories for the user to choose from.

  • max_tools ¤
    (int, default: 0 ) –

    Maximum tools allowed. 0 for unlimited.

  • min_tools ¤
    (int, default: 0 ) –

    Minimum tools required. 0 for no minimum.

Returns:

utility ¤

Utility protocols for SDK-provided functionality.

These protocols are automatically available to all modules and don't need to be explicitly included in module output unions.

Classes:

EndOfStreamOutput ¤

              flowchart TD
              digitalkin.models.module.utility.EndOfStreamOutput[EndOfStreamOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.EndOfStreamOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.EndOfStreamOutput href "" "digitalkin.models.module.utility.EndOfStreamOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Signal that the stream has ended.

HealthcheckPingInput ¤

              flowchart TD
              digitalkin.models.module.utility.HealthcheckPingInput[HealthcheckPingInput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckPingInput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.HealthcheckPingInput href "" "digitalkin.models.module.utility.HealthcheckPingInput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Input for healthcheck ping request.

HealthcheckPingOutput ¤

              flowchart TD
              digitalkin.models.module.utility.HealthcheckPingOutput[HealthcheckPingOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckPingOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.HealthcheckPingOutput href "" "digitalkin.models.module.utility.HealthcheckPingOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Output for healthcheck ping response.

Simple alive check that returns "pong" status.

HealthcheckServicesInput ¤

              flowchart TD
              digitalkin.models.module.utility.HealthcheckServicesInput[HealthcheckServicesInput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckServicesInput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.HealthcheckServicesInput href "" "digitalkin.models.module.utility.HealthcheckServicesInput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Input for healthcheck services request.

HealthcheckServicesOutput ¤

              flowchart TD
              digitalkin.models.module.utility.HealthcheckServicesOutput[HealthcheckServicesOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckServicesOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.HealthcheckServicesOutput href "" "digitalkin.models.module.utility.HealthcheckServicesOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Output for healthcheck services response.

Reports the health status of all configured services.

HealthcheckStatusInput ¤

              flowchart TD
              digitalkin.models.module.utility.HealthcheckStatusInput[HealthcheckStatusInput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckStatusInput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.HealthcheckStatusInput href "" "digitalkin.models.module.utility.HealthcheckStatusInput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Input for healthcheck status request.

HealthcheckStatusOutput ¤

              flowchart TD
              digitalkin.models.module.utility.HealthcheckStatusOutput[HealthcheckStatusOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckStatusOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.HealthcheckStatusOutput href "" "digitalkin.models.module.utility.HealthcheckStatusOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Output for healthcheck status response.

Comprehensive module status including uptime, active jobs, and metadata.

ModuleStartInfoOutput ¤

              flowchart TD
              digitalkin.models.module.utility.ModuleStartInfoOutput[ModuleStartInfoOutput]
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.ModuleStartInfoOutput
                                digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                



              click digitalkin.models.module.utility.ModuleStartInfoOutput href "" "digitalkin.models.module.utility.ModuleStartInfoOutput"
              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Output sent when module starts with execution context.

This protocol is sent as the first message when a module starts, providing the client with essential execution context information.

ServiceHealthStatus ¤

              flowchart TD
              digitalkin.models.module.utility.ServiceHealthStatus[ServiceHealthStatus]

              

              click digitalkin.models.module.utility.ServiceHealthStatus href "" "digitalkin.models.module.utility.ServiceHealthStatus"
            

Health status of a single service.

UtilityProtocol ¤

              flowchart TD
              digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
              digitalkin.models.module.base_types.DataTrigger[DataTrigger]

                              digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
                


              click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
              click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
            

Base class for SDK-provided utility protocols.

All SDK utility protocols inherit from this class to enable: - Easy identification of SDK vs user-defined protocols - Auto-injection capability - Consistent behavior across the SDK

UtilityRegistry ¤

Registry for SDK-provided built-in triggers.

Example

builtin_triggers = UtilityRegistry.get_builtin_triggers()

Methods:

get_builtin_triggers classmethod ¤
get_builtin_triggers() -> tuple

Get all SDK-provided built-in trigger handlers.

Uses lazy loading to avoid circular imports with the modules package.

Returns:

  • tuple

    Tuple of TriggerHandler subclasses for built-in functionality.

services ¤

This module contains the models for the services.

Modules:

  • cost

    Pydantic models for cost service.

  • registry

    Registry data models.

  • storage

    Storage model.

Classes:

  • BaseMessage

    Base Model representing a simple message in the chat history.

  • BaseRole

    Officially supported Role Enum for chat messages.

  • ChatHistory

    Storage chat history model for the OpenAI Archetype module.

BaseMessage ¤


              flowchart TD
              digitalkin.models.services.BaseMessage[BaseMessage]

              

              click digitalkin.models.services.BaseMessage href "" "digitalkin.models.services.BaseMessage"
            

Base Model representing a simple message in the chat history.

BaseRole ¤


              flowchart TD
              digitalkin.models.services.BaseRole[BaseRole]

              

              click digitalkin.models.services.BaseRole href "" "digitalkin.models.services.BaseRole"
            

Officially supported Role Enum for chat messages.

ChatHistory ¤


              flowchart TD
              digitalkin.models.services.ChatHistory[ChatHistory]

              

              click digitalkin.models.services.ChatHistory href "" "digitalkin.models.services.ChatHistory"
            

Storage chat history model for the OpenAI Archetype module.

cost ¤

Pydantic models for cost service.

Classes:

  • AmountLimit

    Cost limit based on cost amount in dollars (e.g., max $1.00).

  • CostConfig

    Pydantic model that defines a cost configuration.

  • CostEvent

    Pydantic model that represents a cost event registered during service execution.

  • CostTypeEnum

    Enumeration of supported cost types.

  • QuantityLimit

    Cost limit based on quantity (e.g., max 10000 tokens).

AmountLimit ¤

              flowchart TD
              digitalkin.models.services.cost.AmountLimit[AmountLimit]

              

              click digitalkin.models.services.cost.AmountLimit href "" "digitalkin.models.services.cost.AmountLimit"
            

Cost limit based on cost amount in dollars (e.g., max $1.00).

CostConfig ¤

              flowchart TD
              digitalkin.models.services.cost.CostConfig[CostConfig]

              

              click digitalkin.models.services.cost.CostConfig href "" "digitalkin.models.services.cost.CostConfig"
            

Pydantic model that defines a cost configuration.

:param cost_name: Name of the cost (unique identifier in the service). :param cost_type: The type/category of the cost. :param description: A short description of the cost. :param unit: The unit of measurement (e.g. token, call, MB). :param rate: The cost per unit (e.g. dollars per token).

CostEvent ¤

              flowchart TD
              digitalkin.models.services.cost.CostEvent[CostEvent]

              

              click digitalkin.models.services.cost.CostEvent href "" "digitalkin.models.services.cost.CostEvent"
            

Pydantic model that represents a cost event registered during service execution.

DEPRECATED¤

:param cost_name: Identifier for the cost configuration. :param cost_type: The type of cost. :param usage: The amount or units consumed. :param cost_amount: The computed cost amount; if not provided it is computed as usage*rate. :param timestamp: The time when the cost event was recorded. :param metadata: Additional contextual information about the cost event.

CostTypeEnum ¤

              flowchart TD
              digitalkin.models.services.cost.CostTypeEnum[CostTypeEnum]

              

              click digitalkin.models.services.cost.CostTypeEnum href "" "digitalkin.models.services.cost.CostTypeEnum"
            

Enumeration of supported cost types.

QuantityLimit ¤

              flowchart TD
              digitalkin.models.services.cost.QuantityLimit[QuantityLimit]

              

              click digitalkin.models.services.cost.QuantityLimit href "" "digitalkin.models.services.cost.QuantityLimit"
            

Cost limit based on quantity (e.g., max 10000 tokens).

registry ¤

Registry data models.

Classes:

ModuleInfo ¤

              flowchart TD
              digitalkin.models.services.registry.ModuleInfo[ModuleInfo]

              

              click digitalkin.models.services.registry.ModuleInfo href "" "digitalkin.models.services.registry.ModuleInfo"
            

Module information from registry.

RegistryModuleStatus ¤

              flowchart TD
              digitalkin.models.services.registry.RegistryModuleStatus[RegistryModuleStatus]

              

              click digitalkin.models.services.registry.RegistryModuleStatus href "" "digitalkin.models.services.registry.RegistryModuleStatus"
            

Module status in the registry.

RegistryModuleType ¤

              flowchart TD
              digitalkin.models.services.registry.RegistryModuleType[RegistryModuleType]

              

              click digitalkin.models.services.registry.RegistryModuleType href "" "digitalkin.models.services.registry.RegistryModuleType"
            

Module type in the registry.

RegistrySetupStatus ¤

              flowchart TD
              digitalkin.models.services.registry.RegistrySetupStatus[RegistrySetupStatus]

              

              click digitalkin.models.services.registry.RegistrySetupStatus href "" "digitalkin.models.services.registry.RegistrySetupStatus"
            

Setup status in the registry.

RegistryVisibility ¤

              flowchart TD
              digitalkin.models.services.registry.RegistryVisibility[RegistryVisibility]

              

              click digitalkin.models.services.registry.RegistryVisibility href "" "digitalkin.models.services.registry.RegistryVisibility"
            

Visibility in the registry.

SetupInfo ¤

              flowchart TD
              digitalkin.models.services.registry.SetupInfo[SetupInfo]

              

              click digitalkin.models.services.registry.SetupInfo href "" "digitalkin.models.services.registry.SetupInfo"
            

Setup information from registry.

storage ¤

Storage model.

Classes:

  • BaseMessage

    Base Model representing a simple message in the chat history.

  • BaseRole

    Officially supported Role Enum for chat messages.

  • ChatHistory

    Storage chat history model for the OpenAI Archetype module.

  • FileHistory

    File history model.

  • FileModel

    File model.

BaseMessage ¤

              flowchart TD
              digitalkin.models.services.storage.BaseMessage[BaseMessage]

              

              click digitalkin.models.services.storage.BaseMessage href "" "digitalkin.models.services.storage.BaseMessage"
            

Base Model representing a simple message in the chat history.

BaseRole ¤

              flowchart TD
              digitalkin.models.services.storage.BaseRole[BaseRole]

              

              click digitalkin.models.services.storage.BaseRole href "" "digitalkin.models.services.storage.BaseRole"
            

Officially supported Role Enum for chat messages.

ChatHistory ¤

              flowchart TD
              digitalkin.models.services.storage.ChatHistory[ChatHistory]

              

              click digitalkin.models.services.storage.ChatHistory href "" "digitalkin.models.services.storage.ChatHistory"
            

Storage chat history model for the OpenAI Archetype module.

FileHistory ¤

              flowchart TD
              digitalkin.models.services.storage.FileHistory[FileHistory]

              

              click digitalkin.models.services.storage.FileHistory href "" "digitalkin.models.services.storage.FileHistory"
            

File history model.

FileModel ¤

              flowchart TD
              digitalkin.models.services.storage.FileModel[FileModel]

              

              click digitalkin.models.services.storage.FileModel href "" "digitalkin.models.services.storage.FileModel"
            

File model.

settings ¤

This package contain settings of sdk.

Modules:

  • server

    Package for server settings.

  • utils

    This package contain channel base.

server ¤

Package for server settings.

Modules:

  • channel

    Server channel settings.

  • grpc

    gRPC server settings for the SDK.

  • server

    Server settings for the DigitalKin application.

channel ¤

Server channel settings.

Classes:

ServerChannelSettings ¤
ServerChannelSettings(**values: Any)

              flowchart TD
              digitalkin.models.settings.server.channel.ServerChannelSettings[ServerChannelSettings]
              digitalkin.models.settings.utils.channel.BaseChannelSettings[BaseChannelSettings]

                              digitalkin.models.settings.utils.channel.BaseChannelSettings --> digitalkin.models.settings.server.channel.ServerChannelSettings
                


              click digitalkin.models.settings.server.channel.ServerChannelSettings href "" "digitalkin.models.settings.server.channel.ServerChannelSettings"
              click digitalkin.models.settings.utils.channel.BaseChannelSettings href "" "digitalkin.models.settings.utils.channel.BaseChannelSettings"
            

Settings for a server channel.

Attributes:

  • advertise_host (str | None) –

    Public hostname/IP sent to registry for discovery. Falls back to host if not set.

  • database_url (str | None) –

    Database URL for registry data storage

Methods:

address property ¤
address: str

Get the server address.

Returns:

  • str

    The formatted address string

validate_credentials ¤
validate_credentials() -> BaseChannelSettings

Validate that credentials are provided when in secure mode.

Returns:

Raises:

validate_port classmethod ¤
validate_port(v: int) -> int

Validate that the port is in a valid range.

Parameters:

  • v ¤ (int) –

    Port number to validate

Returns:

  • int

    The validated port number

Raises:

grpc ¤

gRPC server settings for the SDK.

Classes:

GrpcServerSettings ¤
GrpcServerSettings(**values: Any)

              flowchart TD
              digitalkin.models.settings.server.grpc.GrpcServerSettings[GrpcServerSettings]

              

              click digitalkin.models.settings.server.grpc.GrpcServerSettings href "" "digitalkin.models.settings.server.grpc.GrpcServerSettings"
            

gRPC tuning settings on the SDK side.

Attributes:

  • compression (GrpcCompression) –

    gRPC compression algorithm to use for server responses.

  • keepalive_time (NonNegativeFloat) –

    Interval for server keepalive pings, in milliseconds.

  • keepalive_timeout (NonNegativeFloat) –

    Timeout for server keepalive pings, in milliseconds.

  • min_ping_interval (NonNegativeFloat) –

    Minimum interval between HTTP/2 pings on the server side, in milliseconds.

  • max_receive_message_lenght (NonNegativeFloat) –

    Maximum message size the server can receive, in bytes.

  • max_send_message_length (NonNegativeFloat) –

    Maximum message size the server can send, in bytes.

  • max_pings_without_data (NonNegativeFloat) –

    Maximum number of pings the server allows without receiving any data.

  • keepalive_permit_without_calls (bool) –

    Allow clients to send keepalive pings even when there are no active RPCs.

options property ¤
options: list[tuple[str, Any]]

Convert settings to gRPC server options format.

Returns:

  • list[tuple[str, Any]]

    List of tuples containing gRPC server options and their corresponding values.

server ¤

Server settings for the DigitalKin application.

Classes:

ServerSettings ¤
ServerSettings(**values: Any)

              flowchart TD
              digitalkin.models.settings.server.server.ServerSettings[ServerSettings]

              

              click digitalkin.models.settings.server.server.ServerSettings href "" "digitalkin.models.settings.server.server.ServerSettings"
            

Settings for the DigitalKin server.

Attributes:

  • channel (ServerChannelSettings) –

    Settings for the server channel.

  • grpc (GrpcServerSettings) –

    Settings for the gRPC server.

  • health_check (bool) –

    Whether to enable the health check service.

  • reflection (bool) –

    Whether to enable reflection for the server.

  • max_concurrent_rpcs (NonNegativeInt) –

    Maximum number of RPCs handled in parallel by the server.

  • max_workers (NonNegativeInt) –

    Maximum number of workers for sync mode.

  • thread_pool_workers (NonNegativeInt) –

    Number of workers in the server thread pool.

utils ¤

This package contain channel base.

Modules:

  • channel

    This file define channelBase for grpc config.

channel ¤

This file define channelBase for grpc config.

Classes:

BaseChannelSettings ¤
BaseChannelSettings(**values: Any)

              flowchart TD
              digitalkin.models.settings.utils.channel.BaseChannelSettings[BaseChannelSettings]

              

              click digitalkin.models.settings.utils.channel.BaseChannelSettings href "" "digitalkin.models.settings.utils.channel.BaseChannelSettings"
            

Base settings model for gRPC channel configuration.

Methods:

Attributes:

address property ¤
address: str

Get the server address.

Returns:

  • str

    The formatted address string

validate_credentials ¤
validate_credentials() -> BaseChannelSettings

Validate that credentials are provided when in secure mode.

Returns:

Raises:

validate_port classmethod ¤
validate_port(v: int) -> int

Validate that the port is in a valid range.

Parameters:

  • v ¤ (int) –

    Port number to validate

Returns:

  • int

    The validated port number

Raises:

ControlFlow ¤

              flowchart TD
              digitalkin.models.settings.utils.channel.ControlFlow[ControlFlow]

              

              click digitalkin.models.settings.utils.channel.ControlFlow href "" "digitalkin.models.settings.utils.channel.ControlFlow"
            

Enum for server operation mode.

Credentials ¤
Credentials(**data: Any)

              flowchart TD
              digitalkin.models.settings.utils.channel.Credentials[Credentials]

              

              click digitalkin.models.settings.utils.channel.Credentials href "" "digitalkin.models.settings.utils.channel.Credentials"
            

Model for server credentials in secure mode.

Attributes:

  • key_path (Path | None) –

    Path to the server private key

  • cert_path (Path | None) –

    Path to the server certificate

  • root_cert_path (Path | None) –

    Optional path to the root certificate

Methods:

check_path_exists classmethod ¤
check_path_exists(v: Path | None) -> Path | None

Validate that the file path exists.

Parameters:

  • v ¤ (Path | None) –

    Path to validate

Returns:

  • Path | None

    The validated path

Raises:

SecurityMode ¤

              flowchart TD
              digitalkin.models.settings.utils.channel.SecurityMode[SecurityMode]

              

              click digitalkin.models.settings.utils.channel.SecurityMode href "" "digitalkin.models.settings.utils.channel.SecurityMode"
            

Enum for server security mode.

modules ¤

Module package for DigitalKin.

Modules:

  • archetype_module

    ArchetypeModule extends BaseModule to implement specific module types.

  • tool_module

    ToolModule extends BaseModule to implement specific module types.

  • trigger_handler

    Definition of the Trigger type.

  • triggers

    Built-in SDK triggers.

Classes:

  • ArchetypeModule

    ArchetypeModule extends BaseModule to implement specific module types.

  • ToolModule

    ToolModule extends BaseModule to implement specific module types.

  • TriggerHandler

    Base class for all input-trigger handlers.

ArchetypeModule ¤

ArchetypeModule(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
)

              flowchart TD
              digitalkin.modules.ArchetypeModule[ArchetypeModule]
              digitalkin.modules._base_module.BaseModule[BaseModule]

                              digitalkin.modules._base_module.BaseModule --> digitalkin.modules.ArchetypeModule
                


              click digitalkin.modules.ArchetypeModule href "" "digitalkin.modules.ArchetypeModule"
              click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
            

ArchetypeModule extends BaseModule to implement specific module types.

Parameters:

  • job_id ¤

    (str) –

    Unique job identifier.

  • mission_id ¤

    (str) –

    Mission identifier.

  • setup_id ¤

    (str) –

    Setup identifier.

  • setup_version_id ¤

    (str) –

    Setup version identifier.

  • request_metadata ¤

    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) from the incoming request.

Methods:

Attributes:

status property ¤

status: ModuleStatus

Get the module status.

Returns:

__init_subclass__ ¤

__init_subclass__(**kwargs: Any) -> None

Ensure each subclass has its own copy of mutable class variables.

cleanup abstractmethod async ¤

cleanup() -> None

Run the module.

create_config_setup_model classmethod ¤

create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT

Create the setup model from the setup data.

Parameters:

  • config_setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

Returns:

  • SetupModelT

    The setup model.

create_input_model classmethod ¤

create_input_model(input_data: dict[str, Any]) -> DataModel

Create the input model from the input data.

Parameters:

  • input_data ¤
    (dict[str, Any]) –

    The input data to create the model from.

Returns:

  • DataModel

    The input model, validated against the extended format that

  • DataModel

    includes SDK utility protocols (healthcheck, etc.).

create_output_model classmethod ¤

create_output_model(output_data: dict[str, Any]) -> OutputModelT

Create the output model from the output data.

Parameters:

  • output_data ¤
    (dict[str, Any]) –

    The output data to create the model from.

Returns:

  • OutputModelT

    The output model.

create_secret_model classmethod ¤

create_secret_model(secret_data: dict[str, Any]) -> SecretModelT

Create the secret model from the secret data.

Parameters:

  • secret_data ¤
    (dict[str, Any]) –

    The secret data to create the model from.

Returns:

  • SecretModelT

    The secret model.

create_setup_model async classmethod ¤

create_setup_model(
    setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT

Create the setup model from the setup data.

Creates a filtered setup model instance based on the provided data. Uses get_clean_model() internally to get the appropriate model class with field filtering applied.

Parameters:

  • setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

  • config_fields ¤
    (bool, default: False ) –

    If True, include only fields with json_schema_extra["config"] == True.

Returns:

  • SetupModelT

    An instance of the setup model with the provided data.

discover classmethod ¤

discover() -> None

Discover and register all TriggerHandler subclasses in the specified package or current directory.

Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.

If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.

Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.

get_config_setup_format async classmethod ¤

get_config_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the config setup format model.

The config setup format is used only to initialize the module with configuration data. It includes fields marked with json_schema_extra={"config": True} and excludes hidden runtime fields.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the config setup format as a JSON string.

Raises:

get_cost_format async classmethod ¤

get_cost_format(*, llm_format: bool) -> str

Get the JSON schema of the cost configuration.

Extracts CostConfig from services_config_params["cost"]["config"] and returns as JSON schema.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the cost configuration as a JSON string.

get_input_format async classmethod ¤

get_input_format(*, llm_format: bool) -> str

Get the JSON schema of the input format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the input format as a JSON string.

Raises:

get_module_id classmethod ¤

get_module_id() -> str

Get the module ID from environment variable or metadata.

Returns:

  • str

    The module_id from DIGITALKIN_MODULE_ID env var, or metadata module_id,

  • str

    or "unknown" if neither exists.

get_output_format async classmethod ¤

get_output_format(*, llm_format: bool) -> str

Get the JSON schema of the output format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the output format as a JSON string.

Raises:

get_secret_format async classmethod ¤

get_secret_format(*, llm_format: bool) -> str

Get the JSON schema of the secret format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the secret format as a JSON string.

Raises:

get_select_input_format async classmethod ¤

get_select_input_format() -> str

Get the JSON schema for trigger selection UI.

Returns:

  • str

    The JSON schema with json_schema and ui_schema keys as a JSON string,

  • str

    or empty object if no select_format is defined.

get_setup_format async classmethod ¤

get_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the setup format model.

The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the setup format as a JSON string.

Raises:

initialize abstractmethod async ¤

initialize(context: ModuleContext, setup_data: SetupModelT) -> None

Initialize the module.

register classmethod ¤

Dynamically register the trigger class.

Parameters:

Returns:

run async ¤

run(input_data: InputModelT, setup_data: SetupModelT) -> None

Run the module by dispatching to the appropriate trigger handler.

Parameters:

  • input_data ¤
    (InputModelT) –

    Input data to process.

  • setup_data ¤
    (SetupModelT) –

    Configuration data for the module.

Raises:

  • ValueError

    If no handler for the protocol is found.

run_config_setup async ¤

run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT

Run config setup the module.

The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.

Returns:

  • SetupModelT

    The updated setup model after running the config setup.

start async ¤

start(
    input_data: InputModelT,
    setup_data: SetupModelT,
    callback: Callable[
        [OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
        Coroutine[Any, Any, None],
    ],
    done_callback: Callable | None = None,
) -> None

Start the module.

start_config_setup async ¤

start_config_setup(
    config_setup_data: SetupModelT,
    callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None

Run config setup lifecycle with tool resolution in parallel.

Parameters:

stop async ¤

stop() -> None

Stop the module. Idempotent — second call is a no-op.

ToolModule ¤

ToolModule(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
)

              flowchart TD
              digitalkin.modules.ToolModule[ToolModule]
              digitalkin.modules._base_module.BaseModule[BaseModule]

                              digitalkin.modules._base_module.BaseModule --> digitalkin.modules.ToolModule
                


              click digitalkin.modules.ToolModule href "" "digitalkin.modules.ToolModule"
              click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
            

ToolModule extends BaseModule to implement specific module types.

Parameters:

  • job_id ¤

    (str) –

    Unique job identifier.

  • mission_id ¤

    (str) –

    Mission identifier.

  • setup_id ¤

    (str) –

    Setup identifier.

  • setup_version_id ¤

    (str) –

    Setup version identifier.

  • request_metadata ¤

    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) from the incoming request.

Methods:

Attributes:

status property ¤

status: ModuleStatus

Get the module status.

Returns:

__init_subclass__ ¤

__init_subclass__(**kwargs: Any) -> None

Ensure each subclass has its own copy of mutable class variables.

cleanup abstractmethod async ¤

cleanup() -> None

Run the module.

create_config_setup_model classmethod ¤

create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT

Create the setup model from the setup data.

Parameters:

  • config_setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

Returns:

  • SetupModelT

    The setup model.

create_input_model classmethod ¤

create_input_model(input_data: dict[str, Any]) -> DataModel

Create the input model from the input data.

Parameters:

  • input_data ¤
    (dict[str, Any]) –

    The input data to create the model from.

Returns:

  • DataModel

    The input model, validated against the extended format that

  • DataModel

    includes SDK utility protocols (healthcheck, etc.).

create_output_model classmethod ¤

create_output_model(output_data: dict[str, Any]) -> OutputModelT

Create the output model from the output data.

Parameters:

  • output_data ¤
    (dict[str, Any]) –

    The output data to create the model from.

Returns:

  • OutputModelT

    The output model.

create_secret_model classmethod ¤

create_secret_model(secret_data: dict[str, Any]) -> SecretModelT

Create the secret model from the secret data.

Parameters:

  • secret_data ¤
    (dict[str, Any]) –

    The secret data to create the model from.

Returns:

  • SecretModelT

    The secret model.

create_setup_model async classmethod ¤

create_setup_model(
    setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT

Create the setup model from the setup data.

Creates a filtered setup model instance based on the provided data. Uses get_clean_model() internally to get the appropriate model class with field filtering applied.

Parameters:

  • setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

  • config_fields ¤
    (bool, default: False ) –

    If True, include only fields with json_schema_extra["config"] == True.

Returns:

  • SetupModelT

    An instance of the setup model with the provided data.

discover classmethod ¤

discover() -> None

Discover and register all TriggerHandler subclasses in the specified package or current directory.

Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.

If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.

Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.

get_config_setup_format async classmethod ¤

get_config_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the config setup format model.

The config setup format is used only to initialize the module with configuration data. It includes fields marked with json_schema_extra={"config": True} and excludes hidden runtime fields.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the config setup format as a JSON string.

Raises:

get_cost_format async classmethod ¤

get_cost_format(*, llm_format: bool) -> str

Get the JSON schema of the cost configuration.

Extracts CostConfig from services_config_params["cost"]["config"] and returns as JSON schema.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the cost configuration as a JSON string.

get_input_format async classmethod ¤

get_input_format(*, llm_format: bool) -> str

Get the JSON schema of the input format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the input format as a JSON string.

Raises:

get_module_id classmethod ¤

get_module_id() -> str

Get the module ID from environment variable or metadata.

Returns:

  • str

    The module_id from DIGITALKIN_MODULE_ID env var, or metadata module_id,

  • str

    or "unknown" if neither exists.

get_output_format async classmethod ¤

get_output_format(*, llm_format: bool) -> str

Get the JSON schema of the output format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the output format as a JSON string.

Raises:

get_secret_format async classmethod ¤

get_secret_format(*, llm_format: bool) -> str

Get the JSON schema of the secret format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the secret format as a JSON string.

Raises:

get_select_input_format async classmethod ¤

get_select_input_format() -> str

Get the JSON schema for trigger selection UI.

Returns:

  • str

    The JSON schema with json_schema and ui_schema keys as a JSON string,

  • str

    or empty object if no select_format is defined.

get_setup_format async classmethod ¤

get_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the setup format model.

The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the setup format as a JSON string.

Raises:

initialize abstractmethod async ¤

initialize(context: ModuleContext, setup_data: SetupModelT) -> None

Initialize the module.

register classmethod ¤

Dynamically register the trigger class.

Parameters:

Returns:

run async ¤

run(input_data: InputModelT, setup_data: SetupModelT) -> None

Run the module by dispatching to the appropriate trigger handler.

Parameters:

  • input_data ¤
    (InputModelT) –

    Input data to process.

  • setup_data ¤
    (SetupModelT) –

    Configuration data for the module.

Raises:

  • ValueError

    If no handler for the protocol is found.

run_config_setup async ¤

run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT

Run config setup the module.

The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.

Returns:

  • SetupModelT

    The updated setup model after running the config setup.

start async ¤

start(
    input_data: InputModelT,
    setup_data: SetupModelT,
    callback: Callable[
        [OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
        Coroutine[Any, Any, None],
    ],
    done_callback: Callable | None = None,
) -> None

Start the module.

start_config_setup async ¤

start_config_setup(
    config_setup_data: SetupModelT,
    callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None

Run config setup lifecycle with tool resolution in parallel.

Parameters:

stop async ¤

stop() -> None

Stop the module. Idempotent — second call is a no-op.

TriggerHandler ¤

TriggerHandler(context: ModuleContext)

              flowchart TD
              digitalkin.modules.TriggerHandler[TriggerHandler]
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.TriggerHandler
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                



              click digitalkin.modules.TriggerHandler href "" "digitalkin.modules.TriggerHandler"
              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Base class for all input-trigger handlers.

Each handler declares
  • protocol_key: the Literal value this handler processes
  • handle(): logic to process the validated payload

Methods:

  • add_cost

    Add a cost entry using the cost strategy.

  • append_files_history

    Append files to file history.

  • clear_fh_mission_cache

    Remove a mission's entries from in-memory caches after flush.

  • flush_file_history

    Flush the current mission's dirty file history to storage.

  • get_cost

    Get cost entries for a specific name.

  • get_costs

    Get filtered cost entries.

  • handle

    Asynchronously processes the input data specific to Handler and streams results via the provided callback.

  • load_file_history

    Load file history for the current session.

  • log_debug

    Log debug message using the callbacks strategy.

  • log_error

    Log error message using the callbacks strategy.

  • log_info

    Log info message using the callbacks strategy.

  • log_warning

    Log warning message using the callbacks strategy.

  • read_storage

    Read data from storage.

  • send_message

    Convert agent event to AG-UI protocol and send via context callbacks.

  • store_storage

    Store data using the storage strategy.

  • update_storage

    Update existing data in storage.

  • upsert_storage

    Insert or update data in storage atomically.

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤
    (str) –

    Name of the cost configuration to use.

  • quantity ¤
    (float) –

    Quantity of units consumed.

append_files_history async ¤

append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤

clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤

flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤

get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤
    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

handle abstractmethod async ¤

handle(
    input_data: InputModelT, setup_data: SetupModelT, context: ModuleContext
) -> None

Asynchronously processes the input data specific to Handler and streams results via the provided callback.

Parameters:

  • input_data ¤
    (InputModelT) –

    The input data to be processed by the handler.

  • setup_data ¤
    (SetupModelT) –

    The setup or configuration data required for processing.

  • context ¤
    (ModuleContext) –

    The context object containing module-specific information and resources.

Returns:

  • Any ( None ) –

    The result of the processing, if applicable.

Note

self.send_message: callback used to stream results. (Callable[[OutputModelT], Coroutine[Any, Any, None]])

The callback must be awaited to ensure results are streamed correctly during processing.

load_file_history async ¤

load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤

log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤

log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤

log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤

log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤

send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤

store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤

update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤

upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

archetype_module ¤

ArchetypeModule extends BaseModule to implement specific module types.

Classes:

  • ArchetypeModule

    ArchetypeModule extends BaseModule to implement specific module types.

ArchetypeModule ¤

ArchetypeModule(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
)

              flowchart TD
              digitalkin.modules.archetype_module.ArchetypeModule[ArchetypeModule]
              digitalkin.modules._base_module.BaseModule[BaseModule]

                              digitalkin.modules._base_module.BaseModule --> digitalkin.modules.archetype_module.ArchetypeModule
                


              click digitalkin.modules.archetype_module.ArchetypeModule href "" "digitalkin.modules.archetype_module.ArchetypeModule"
              click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
            

ArchetypeModule extends BaseModule to implement specific module types.

Parameters:

  • job_id ¤
    (str) –

    Unique job identifier.

  • mission_id ¤
    (str) –

    Mission identifier.

  • setup_id ¤
    (str) –

    Setup identifier.

  • setup_version_id ¤
    (str) –

    Setup version identifier.

  • request_metadata ¤
    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) from the incoming request.

Methods:

Attributes:

status property ¤
status: ModuleStatus

Get the module status.

Returns:

__init_subclass__ ¤
__init_subclass__(**kwargs: Any) -> None

Ensure each subclass has its own copy of mutable class variables.

cleanup abstractmethod async ¤
cleanup() -> None

Run the module.

create_config_setup_model classmethod ¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT

Create the setup model from the setup data.

Parameters:

  • config_setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

Returns:

  • SetupModelT

    The setup model.

create_input_model classmethod ¤
create_input_model(input_data: dict[str, Any]) -> DataModel

Create the input model from the input data.

Parameters:

  • input_data ¤
    (dict[str, Any]) –

    The input data to create the model from.

Returns:

  • DataModel

    The input model, validated against the extended format that

  • DataModel

    includes SDK utility protocols (healthcheck, etc.).

create_output_model classmethod ¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT

Create the output model from the output data.

Parameters:

  • output_data ¤
    (dict[str, Any]) –

    The output data to create the model from.

Returns:

  • OutputModelT

    The output model.

create_secret_model classmethod ¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT

Create the secret model from the secret data.

Parameters:

  • secret_data ¤
    (dict[str, Any]) –

    The secret data to create the model from.

Returns:

  • SecretModelT

    The secret model.

create_setup_model async classmethod ¤
create_setup_model(
    setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT

Create the setup model from the setup data.

Creates a filtered setup model instance based on the provided data. Uses get_clean_model() internally to get the appropriate model class with field filtering applied.

Parameters:

  • setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

  • config_fields ¤
    (bool, default: False ) –

    If True, include only fields with json_schema_extra["config"] == True.

Returns:

  • SetupModelT

    An instance of the setup model with the provided data.

discover classmethod ¤
discover() -> None

Discover and register all TriggerHandler subclasses in the specified package or current directory.

Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.

If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.

Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.

get_config_setup_format async classmethod ¤
get_config_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the config setup format model.

The config setup format is used only to initialize the module with configuration data. It includes fields marked with json_schema_extra={"config": True} and excludes hidden runtime fields.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the config setup format as a JSON string.

Raises:

get_cost_format async classmethod ¤
get_cost_format(*, llm_format: bool) -> str

Get the JSON schema of the cost configuration.

Extracts CostConfig from services_config_params["cost"]["config"] and returns as JSON schema.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the cost configuration as a JSON string.

get_input_format async classmethod ¤
get_input_format(*, llm_format: bool) -> str

Get the JSON schema of the input format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the input format as a JSON string.

Raises:

get_module_id classmethod ¤
get_module_id() -> str

Get the module ID from environment variable or metadata.

Returns:

  • str

    The module_id from DIGITALKIN_MODULE_ID env var, or metadata module_id,

  • str

    or "unknown" if neither exists.

get_output_format async classmethod ¤
get_output_format(*, llm_format: bool) -> str

Get the JSON schema of the output format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the output format as a JSON string.

Raises:

get_secret_format async classmethod ¤
get_secret_format(*, llm_format: bool) -> str

Get the JSON schema of the secret format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the secret format as a JSON string.

Raises:

get_select_input_format async classmethod ¤
get_select_input_format() -> str

Get the JSON schema for trigger selection UI.

Returns:

  • str

    The JSON schema with json_schema and ui_schema keys as a JSON string,

  • str

    or empty object if no select_format is defined.

get_setup_format async classmethod ¤
get_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the setup format model.

The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the setup format as a JSON string.

Raises:

initialize abstractmethod async ¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None

Initialize the module.

register classmethod ¤

Dynamically register the trigger class.

Parameters:

Returns:

run async ¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None

Run the module by dispatching to the appropriate trigger handler.

Parameters:

  • input_data ¤
    (InputModelT) –

    Input data to process.

  • setup_data ¤
    (SetupModelT) –

    Configuration data for the module.

Raises:

  • ValueError

    If no handler for the protocol is found.

run_config_setup async ¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT

Run config setup the module.

The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.

Returns:

  • SetupModelT

    The updated setup model after running the config setup.

start async ¤
start(
    input_data: InputModelT,
    setup_data: SetupModelT,
    callback: Callable[
        [OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
        Coroutine[Any, Any, None],
    ],
    done_callback: Callable | None = None,
) -> None

Start the module.

start_config_setup async ¤
start_config_setup(
    config_setup_data: SetupModelT,
    callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None

Run config setup lifecycle with tool resolution in parallel.

Parameters:

stop async ¤
stop() -> None

Stop the module. Idempotent — second call is a no-op.

tool_module ¤

ToolModule extends BaseModule to implement specific module types.

Classes:

  • ToolModule

    ToolModule extends BaseModule to implement specific module types.

ToolModule ¤

ToolModule(
    job_id: str,
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    request_metadata: dict[str, str] | None = None,
)

              flowchart TD
              digitalkin.modules.tool_module.ToolModule[ToolModule]
              digitalkin.modules._base_module.BaseModule[BaseModule]

                              digitalkin.modules._base_module.BaseModule --> digitalkin.modules.tool_module.ToolModule
                


              click digitalkin.modules.tool_module.ToolModule href "" "digitalkin.modules.tool_module.ToolModule"
              click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
            

ToolModule extends BaseModule to implement specific module types.

Parameters:

  • job_id ¤
    (str) –

    Unique job identifier.

  • mission_id ¤
    (str) –

    Mission identifier.

  • setup_id ¤
    (str) –

    Setup identifier.

  • setup_version_id ¤
    (str) –

    Setup version identifier.

  • request_metadata ¤
    (dict[str, str] | None, default: None ) –

    gRPC request metadata (headers) from the incoming request.

Methods:

Attributes:

status property ¤
status: ModuleStatus

Get the module status.

Returns:

__init_subclass__ ¤
__init_subclass__(**kwargs: Any) -> None

Ensure each subclass has its own copy of mutable class variables.

cleanup abstractmethod async ¤
cleanup() -> None

Run the module.

create_config_setup_model classmethod ¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT

Create the setup model from the setup data.

Parameters:

  • config_setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

Returns:

  • SetupModelT

    The setup model.

create_input_model classmethod ¤
create_input_model(input_data: dict[str, Any]) -> DataModel

Create the input model from the input data.

Parameters:

  • input_data ¤
    (dict[str, Any]) –

    The input data to create the model from.

Returns:

  • DataModel

    The input model, validated against the extended format that

  • DataModel

    includes SDK utility protocols (healthcheck, etc.).

create_output_model classmethod ¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT

Create the output model from the output data.

Parameters:

  • output_data ¤
    (dict[str, Any]) –

    The output data to create the model from.

Returns:

  • OutputModelT

    The output model.

create_secret_model classmethod ¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT

Create the secret model from the secret data.

Parameters:

  • secret_data ¤
    (dict[str, Any]) –

    The secret data to create the model from.

Returns:

  • SecretModelT

    The secret model.

create_setup_model async classmethod ¤
create_setup_model(
    setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT

Create the setup model from the setup data.

Creates a filtered setup model instance based on the provided data. Uses get_clean_model() internally to get the appropriate model class with field filtering applied.

Parameters:

  • setup_data ¤
    (dict[str, Any]) –

    The setup data to create the model from.

  • config_fields ¤
    (bool, default: False ) –

    If True, include only fields with json_schema_extra["config"] == True.

Returns:

  • SetupModelT

    An instance of the setup model with the provided data.

discover classmethod ¤
discover() -> None

Discover and register all TriggerHandler subclasses in the specified package or current directory.

Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.

If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.

Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.

get_config_setup_format async classmethod ¤
get_config_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the config setup format model.

The config setup format is used only to initialize the module with configuration data. It includes fields marked with json_schema_extra={"config": True} and excludes hidden runtime fields.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the config setup format as a JSON string.

Raises:

get_cost_format async classmethod ¤
get_cost_format(*, llm_format: bool) -> str

Get the JSON schema of the cost configuration.

Extracts CostConfig from services_config_params["cost"]["config"] and returns as JSON schema.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the cost configuration as a JSON string.

get_input_format async classmethod ¤
get_input_format(*, llm_format: bool) -> str

Get the JSON schema of the input format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the input format as a JSON string.

Raises:

get_module_id classmethod ¤
get_module_id() -> str

Get the module ID from environment variable or metadata.

Returns:

  • str

    The module_id from DIGITALKIN_MODULE_ID env var, or metadata module_id,

  • str

    or "unknown" if neither exists.

get_output_format async classmethod ¤
get_output_format(*, llm_format: bool) -> str

Get the JSON schema of the output format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the output format as a JSON string.

Raises:

get_secret_format async classmethod ¤
get_secret_format(*, llm_format: bool) -> str

Get the JSON schema of the secret format model.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the secret format as a JSON string.

Raises:

get_select_input_format async classmethod ¤
get_select_input_format() -> str

Get the JSON schema for trigger selection UI.

Returns:

  • str

    The JSON schema with json_schema and ui_schema keys as a JSON string,

  • str

    or empty object if no select_format is defined.

get_setup_format async classmethod ¤
get_setup_format(*, llm_format: bool) -> str

Gets the JSON schema of the setup format model.

The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.

Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.

Parameters:

  • llm_format ¤
    (bool) –

    If True, return LLM-optimized schema format with inlined references and simplified structure.

Returns:

  • str

    The JSON schema of the setup format as a JSON string.

Raises:

initialize abstractmethod async ¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None

Initialize the module.

register classmethod ¤

Dynamically register the trigger class.

Parameters:

Returns:

run async ¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None

Run the module by dispatching to the appropriate trigger handler.

Parameters:

  • input_data ¤
    (InputModelT) –

    Input data to process.

  • setup_data ¤
    (SetupModelT) –

    Configuration data for the module.

Raises:

  • ValueError

    If no handler for the protocol is found.

run_config_setup async ¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT

Run config setup the module.

The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.

Returns:

  • SetupModelT

    The updated setup model after running the config setup.

start async ¤
start(
    input_data: InputModelT,
    setup_data: SetupModelT,
    callback: Callable[
        [OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
        Coroutine[Any, Any, None],
    ],
    done_callback: Callable | None = None,
) -> None

Start the module.

start_config_setup async ¤
start_config_setup(
    config_setup_data: SetupModelT,
    callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None

Run config setup lifecycle with tool resolution in parallel.

Parameters:

stop async ¤
stop() -> None

Stop the module. Idempotent — second call is a no-op.

trigger_handler ¤

Definition of the Trigger type.

Classes:

TriggerHandler ¤

TriggerHandler(context: ModuleContext)

              flowchart TD
              digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                



              click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Base class for all input-trigger handlers.

Each handler declares
  • protocol_key: the Literal value this handler processes
  • handle(): logic to process the validated payload

Methods:

  • add_cost

    Add a cost entry using the cost strategy.

  • append_files_history

    Append files to file history.

  • clear_fh_mission_cache

    Remove a mission's entries from in-memory caches after flush.

  • flush_file_history

    Flush the current mission's dirty file history to storage.

  • get_cost

    Get cost entries for a specific name.

  • get_costs

    Get filtered cost entries.

  • handle

    Asynchronously processes the input data specific to Handler and streams results via the provided callback.

  • load_file_history

    Load file history for the current session.

  • log_debug

    Log debug message using the callbacks strategy.

  • log_error

    Log error message using the callbacks strategy.

  • log_info

    Log info message using the callbacks strategy.

  • log_warning

    Log warning message using the callbacks strategy.

  • read_storage

    Read data from storage.

  • send_message

    Convert agent event to AG-UI protocol and send via context callbacks.

  • store_storage

    Store data using the storage strategy.

  • update_storage

    Update existing data in storage.

  • upsert_storage

    Insert or update data in storage atomically.

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤
    (str) –

    Name of the cost configuration to use.

  • quantity ¤
    (float) –

    Quantity of units consumed.

append_files_history async ¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤
clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤
flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤
    (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤
get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤
    (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

handle abstractmethod async ¤
handle(
    input_data: InputModelT, setup_data: SetupModelT, context: ModuleContext
) -> None

Asynchronously processes the input data specific to Handler and streams results via the provided callback.

Parameters:

  • input_data ¤
    (InputModelT) –

    The input data to be processed by the handler.

  • setup_data ¤
    (SetupModelT) –

    The setup or configuration data required for processing.

  • context ¤
    (ModuleContext) –

    The context object containing module-specific information and resources.

Returns:

  • Any ( None ) –

    The result of the processing, if applicable.

Note

self.send_message: callback used to stream results. (Callable[[OutputModelT], Coroutine[Any, Any, None]])

The callback must be awaited to ensure results are streamed correctly during processing.

load_file_history async ¤
load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤
    (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤
    (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name for the data

  • record_id ¤
    (str | None) –

    Optional record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤
    (str) –

    Collection name

  • record_id ¤
    (str) –

    Record identifier

  • data ¤
    (dict[str, Any]) –

    Data to store or update

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

triggers ¤

Built-in SDK triggers.

These triggers are automatically registered without requiring discovery. They provide standard functionality available to all modules.

Note: These are internal triggers. External code should not import them directly. Use UtilityRegistry.get_builtin_triggers() to access the trigger classes.

Modules:

healthcheck_ping_trigger ¤

Healthcheck ping trigger - simple alive check.

Classes:

HealthcheckPingTrigger ¤
HealthcheckPingTrigger(context: ModuleContext)

              flowchart TD
              digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger[HealthcheckPingTrigger]
              digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.modules.trigger_handler.TriggerHandler --> digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger
                                digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                


                digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                



              click digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger href "" "digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger"
              click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Handler for simple ping healthcheck.

Responds immediately with "pong" status to verify the module is responsive.

Methods:

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤ (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤ (str) –

    Name of the cost configuration to use.

  • quantity ¤ (float) –

    Quantity of units consumed.

append_files_history async ¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤
clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤ (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤
flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤ (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤
get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤ (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤ (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

handle async ¤

Handle ping healthcheck request.

Parameters:

  • input_data ¤ (HealthcheckPingInput) –

    The input trigger data (unused for healthcheck).

  • setup_data ¤ (Any) –

    The setup configuration (unused for healthcheck).

  • context ¤ (ModuleContext) –

    The module context.

load_file_history async ¤
load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name for the data

  • record_id ¤ (str | None) –

    Optional record identifier

  • data ¤ (dict[str, Any]) –

    Data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

  • data ¤ (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

  • data ¤ (dict[str, Any]) –

    Data to store or update

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

healthcheck_services_trigger ¤

Healthcheck services trigger - reports service health.

Classes:

HealthcheckServicesTrigger ¤
HealthcheckServicesTrigger(context: ModuleContext)

              flowchart TD
              digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger[HealthcheckServicesTrigger]
              digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.modules.trigger_handler.TriggerHandler --> digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger
                                digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                


                digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                



              click digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger href "" "digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger"
              click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Handler for services healthcheck.

Reports the health status of all configured services (storage, cost, filesystem, etc.).

Methods:

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤ (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤ (str) –

    Name of the cost configuration to use.

  • quantity ¤ (float) –

    Quantity of units consumed.

append_files_history async ¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤
clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤ (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤
flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤ (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤
get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤ (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤ (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

handle async ¤

Handle services healthcheck request.

Parameters:

load_file_history async ¤
load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name for the data

  • record_id ¤ (str | None) –

    Optional record identifier

  • data ¤ (dict[str, Any]) –

    Data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

  • data ¤ (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

  • data ¤ (dict[str, Any]) –

    Data to store or update

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

healthcheck_status_trigger ¤

Healthcheck status trigger - comprehensive module status.

Classes:

HealthcheckStatusTrigger ¤
HealthcheckStatusTrigger(context: ModuleContext)

              flowchart TD
              digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger[HealthcheckStatusTrigger]
              digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
              digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
              digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
              digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
              digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
              digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
              digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]

                              digitalkin.modules.trigger_handler.TriggerHandler --> digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger
                                digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                


                digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger
                                digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
                
                digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
                                digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                
                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
                

                digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
                



              click digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger href "" "digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger"
              click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
              click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
              click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
              click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
              click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
              click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
              click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
            

Handler for comprehensive status healthcheck.

Reports detailed module status including uptime, active jobs, and metadata.

Methods:

add_cost async staticmethod ¤

Add a cost entry using the cost strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤ (str) –

    Name/identifier for this cost entry.

  • cost_config_name ¤ (str) –

    Name of the cost configuration to use.

  • quantity ¤ (float) –

    Quantity of units consumed.

append_files_history async ¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None

Append files to file history.

Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().

Parameters:

clear_fh_mission_cache ¤
clear_fh_mission_cache(context: ModuleContext) -> None

Remove a mission's entries from in-memory caches after flush.

Parameters:

  • context ¤ (ModuleContext) –

    Module context identifying the mission to clear.

flush_file_history async ¤
flush_file_history(context: ModuleContext) -> None

Flush the current mission's dirty file history to storage.

Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing storage strategy.

get_cost async staticmethod ¤

Get cost entries for a specific name.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • name ¤ (str) –

    Name/identifier to get costs for.

Returns:

  • list[CostData]

    List of cost data entries, empty on failure.

get_costs async staticmethod ¤
get_costs(
    context: ModuleContext,
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered cost entries.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the cost strategy.

  • names ¤ (list[str] | None, default: None ) –

    Optional list of names to filter by.

  • cost_types ¤ (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    Optional list of cost types to filter by.

Returns:

  • list[CostData]

    List of filtered cost data entries, empty on failure.

handle async ¤

Handle status healthcheck request.

Parameters:

load_file_history async ¤
load_file_history(context: ModuleContext) -> FileHistory

Load file history for the current session.

Returns cached history on subsequent calls to avoid gRPC reads.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing storage strategy.

Returns:

  • FileHistory

    File history object, empty if none exists or loading fails.

log_debug staticmethod ¤
log_debug(context: ModuleContext, message: str, *args: Any) -> None

Log debug message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Debug message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_error staticmethod ¤
log_error(context: ModuleContext, message: str, *args: Any) -> None

Log error message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Error message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_info staticmethod ¤
log_info(context: ModuleContext, message: str, *args: Any) -> None

Log info message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Info message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

log_warning staticmethod ¤
log_warning(context: ModuleContext, message: str, *args: Any) -> None

Log warning message using the callbacks strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the callbacks strategy

  • message ¤ (str) –

    Warning message to log (supports %s lazy formatting)

  • *args ¤ (Any, default: () ) –

    Format arguments for lazy string interpolation

read_storage async staticmethod ¤

Read data from storage.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

Returns:

Raises:

  • StorageServiceError

    If read operation fails

send_message async ¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None

Convert agent event to AG-UI protocol and send via context callbacks.

Parameters:

store_storage async staticmethod ¤
store_storage(
    context: ModuleContext,
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Store data using the storage strategy.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name for the data

  • record_id ¤ (str | None) –

    Optional record identifier

  • data ¤ (dict[str, Any]) –

    Data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If storage operation fails

update_storage async staticmethod ¤
update_storage(
    context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None

Update existing data in storage.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

  • data ¤ (dict[str, Any]) –

    Updated data

Returns:

Raises:

  • StorageServiceError

    If update operation fails

upsert_storage async staticmethod ¤
upsert_storage(
    context: ModuleContext,
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord

Insert or update data in storage atomically.

Parameters:

  • context ¤ (ModuleContext) –

    Module context containing the storage strategy

  • collection ¤ (str) –

    Collection name

  • record_id ¤ (str) –

    Record identifier

  • data ¤ (dict[str, Any]) –

    Data to store or update

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    Type of data being stored

Returns:

Raises:

  • StorageServiceError

    If upsert operation fails

services ¤

This package contains the abstract base class for all services.

Modules:

  • agent

    This module is responsible for handling the agent services.

  • base_strategy

    This module contains the abstract base class for storage strategies.

  • communication

    Communication service for module-to-module interaction.

  • cost

    This module is responsible for handling the cost services.

  • filesystem

    This module is responsible for handling the filesystem services.

  • identity

    This module is responsible for handling the identity service.

  • registry

    This module is responsible for handling the registry service.

  • services_config

    Service Provider definitions.

  • services_models

    This module contains the strategy models for the services.

  • setup

    This module is responsible for handling the setup service.

  • snapshot

    This module is responsible for handling the snapshot service.

  • storage

    This module is responsible for handling the storage service.

  • task_manager

    Task manager signal service.

  • user_profile

    UserProfile service package.

Classes:

AgentStrategy ¤


              flowchart TD
              digitalkin.services.AgentStrategy[AgentStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.AgentStrategy
                


              click digitalkin.services.AgentStrategy href "" "digitalkin.services.AgentStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for agent strategies.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • start

    Start the agent.

  • stop

    Stop the agent.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

start abstractmethod ¤

start() -> None

Start the agent.

stop abstractmethod ¤

stop() -> None

Stop the agent.

CommunicationStrategy ¤

CommunicationStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.CommunicationStrategy
                


              click digitalkin.services.CommunicationStrategy href "" "digitalkin.services.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for module-to-module communication.

This service enables: - Archetype → Tool communication - Archetype → Archetype communication - Tool → Tool communication - Any module → Any module communication

The service wraps the Module Service protocol from agentic-mesh-protocol.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • call_module

    Call a module and stream responses.

  • close

    Release communication resources (channels, connection pools).

  • get_module_schemas

    Get module schemas (input/output/setup/secret/cost).

call_module abstractmethod async ¤

call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call a module and stream responses.

Uses Module Service StartModule RPC to execute the module. Streams responses as they are generated by the module.

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • input_data ¤
    (dict) –

    Input data as dictionary

  • setup_id ¤
    (str) –

    Setup configuration ID

  • mission_id ¤
    (str) –

    Mission context ID

  • callback ¤
    (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback for each response

  • metadata ¤
    (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers) to send with the request.

Yields:

close abstractmethod async ¤

close() -> None

Release communication resources (channels, connection pools).

get_module_schemas abstractmethod async ¤

get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas (input/output/setup/secret/cost).

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • llm_format ¤
    (bool, default: False ) –

    Return LLM-friendly format (simplified schema). Note: cost always returns actual data regardless of this flag.

Returns:

  • dict[str, dict]

    Dictionary containing schemas:

  • dict[str, dict]

    { "input": {...}, "output": {...}, "setup": {...}, "secret": {...}, "cost": {...}

  • dict[str, dict]

    }

CostStrategy ¤


              flowchart TD
              digitalkin.services.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.CostStrategy
                


              click digitalkin.services.CostStrategy href "" "digitalkin.services.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for cost strategies.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • add

    Register a new cost.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • get

    Get a cost.

  • get_cost_config

    Get cost configuration for the current setup version.

  • get_filtered

    Get filtered costs.

  • set_cost_config

    Store cost configuration for the current setup version.

  • set_limits

    Set cost limits for this session.

add abstractmethod async ¤

add(name: str, cost_config_name: str, quantity: float) -> None

Register a new cost.

check_limit abstractmethod async ¤

check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤
    (str) –

    Name of the cost config.

  • quantity ¤
    (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

get abstractmethod async ¤

get(name: str) -> list[CostData]

Get a cost.

get_cost_config abstractmethod async ¤

get_cost_config() -> list[CostConfig]

Get cost configuration for the current setup version.

Returns:

get_filtered abstractmethod async ¤

get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered costs.

set_cost_config abstractmethod async ¤

set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration for the current setup version.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits abstractmethod async ¤

set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

DefaultAgent ¤


              flowchart TD
              digitalkin.services.DefaultAgent[DefaultAgent]
              digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.agent.agent_strategy.AgentStrategy --> digitalkin.services.DefaultAgent
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
                



              click digitalkin.services.DefaultAgent href "" "digitalkin.services.DefaultAgent"
              click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default agent implementation for the agent service.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • start

    Start the agent.

  • stop

    Stop the agent.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

start ¤

start() -> None

Start the agent.

stop ¤

stop() -> None

Stop the agent.

DefaultCommunication ¤

DefaultCommunication(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.DefaultCommunication[DefaultCommunication]
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.DefaultCommunication
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                



              click digitalkin.services.DefaultCommunication href "" "digitalkin.services.DefaultCommunication"
              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default communication strategy (local implementation).

This implementation is primarily for testing and development. For production, use GrpcCommunication to connect to remote modules.

Parameters:

  • mission_id ¤

    (str) –

    Mission identifier

  • setup_id ¤

    (str) –

    Setup identifier

  • setup_version_id ¤

    (str) –

    Setup version identifier

Methods:

  • call_module

    Call module (local implementation yields empty response).

  • close

    No-op for local communication.

  • get_module_schemas

    Get module schemas (local implementation returns empty schemas).

call_module async ¤

call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call module (local implementation yields empty response).

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • input_data ¤
    (dict) –

    Input data

  • setup_id ¤
    (str) –

    Setup ID

  • mission_id ¤
    (str) –

    Mission ID

  • callback ¤
    (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback

  • metadata ¤
    (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers).

Yields:

close async ¤

close() -> None

No-op for local communication.

get_module_schemas async ¤

get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas (local implementation returns empty schemas).

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • llm_format ¤
    (bool, default: False ) –

    Return LLM-friendly format

Returns:

DefaultCost ¤


              flowchart TD
              digitalkin.services.DefaultCost[DefaultCost]
              digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.DefaultCost
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
                



              click digitalkin.services.DefaultCost href "" "digitalkin.services.DefaultCost"
              click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default cost strategy.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

  • config ¤

    (dict[str, CostConfig]) –

    The configuration dictionary for the cost

Methods:

  • add

    Create a new record in the cost database.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • get

    Get a record from the database.

  • get_cost_config

    Get cost configuration from in-memory config.

  • get_filtered

    Get records from the database.

  • set_cost_config

    Store cost configuration in memory.

  • set_limits

    Set cost limits for this session.

add async ¤

Create a new record in the cost database.

Parameters:

  • name ¤
    (str) –

    The name of the cost

  • cost_config_name ¤
    (str) –

    The name of the cost config

  • quantity ¤
    (float) –

    The quantity of the cost

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost already exists

check_limit async ¤

check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤
    (str) –

    Name of the cost config.

  • quantity ¤
    (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

get async ¤

get(name: str) -> list[CostData]

Get a record from the database.

Parameters:

  • name ¤
    (str) –

    The name of the cost

Returns:

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost does not exist

get_cost_config async ¤

get_cost_config() -> list[CostConfig]

Get cost configuration from in-memory config.

Returns:

  • list[CostConfig]

    List of CostConfig objects from the config dictionary.

get_filtered async ¤

get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get records from the database.

Parameters:

  • names ¤
    (list[str] | None, default: None ) –

    The names of the costs

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    The types of the costs

Returns:

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost does not exist

set_cost_config async ¤

set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration in memory.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits async ¤

set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

DefaultFilesystem ¤

DefaultFilesystem(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.DefaultFilesystem[DefaultFilesystem]
              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.DefaultFilesystem
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
                



              click digitalkin.services.DefaultFilesystem href "" "digitalkin.services.DefaultFilesystem"
              click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default filesystem implementation.

This implementation provides a local filesystem-based storage solution with support for all filesystem operations defined in the strategy. Files are stored in a temporary directory with proper metadata tracking.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • delete_files

    Delete multiple files.

  • get_file

    Get a specific file by ID or name.

  • get_files

    List files with filtering, sorting, and pagination.

  • update_file

    Update file metadata, content, or both.

  • upload_files

    Upload multiple files to the system.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

delete_files async ¤

delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files.

This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files to delete

  • permanent ¤
    (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤
    (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

Raises:

get_file async ¤

get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a specific file by ID or name.

This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be retrieved

  • context ¤
    (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

get_files async ¤

get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

List files with filtering, sorting, and pagination.

This method provides flexible file querying capabilities with support for: - Multiple filter criteria (name, type, dates, size, etc.) - Pagination for large result sets - Sorting by various fields - Scoped access by context

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • list_size ¤
    (int, default: 100 ) –

    Number of files to return per page

  • offset ¤
    (int, default: 0 ) –

    Offset to start listing files from

  • order ¤
    (str | None, default: None ) –

    Fields to order results by (example: "created_at:asc,name:desc")

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

update_file async ¤

update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update file metadata, content, or both.

This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions

Parameters:

  • file_id ¤
    (str) –

    The id of the file to be updated

  • content ¤
    (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤
    (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤
    (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤
    (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤
    (str | None, default: None ) –

    Optional new name for the file

  • status ¤
    (str | None, default: None ) –

    Optional new status for the file

Returns:

Raises:

upload_files async ¤

Upload multiple files to the system.

This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.

Parameters:

Returns:

Raises:

DefaultIdentity ¤


              flowchart TD
              digitalkin.services.DefaultIdentity[DefaultIdentity]
              digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.identity.identity_strategy.IdentityStrategy --> digitalkin.services.DefaultIdentity
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
                



              click digitalkin.services.DefaultIdentity href "" "digitalkin.services.DefaultIdentity"
              click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

DefaultIdentity is the default identity strategy.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_identity

    Get the identity.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

get_identity async ¤

get_identity() -> str

Get the identity.

Returns:

  • str ( str ) –

    The identity

DefaultRegistry ¤

DefaultRegistry(*args: Any, **kwargs: Any)

              flowchart TD
              digitalkin.services.DefaultRegistry[DefaultRegistry]
              digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.DefaultRegistry
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
                



              click digitalkin.services.DefaultRegistry href "" "digitalkin.services.DefaultRegistry"
              click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default registry strategy using in-memory storage.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • get_setup

    Get setup info (not supported in default registry).

  • get_status

    Get module status.

  • heartbeat

    Send heartbeat to keep module active.

  • register

    Register a module with the registry.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

deregister async ¤

deregister(module_id: str) -> bool

Deregister a module from the registry.

Parameters:

  • module_id ¤
    (str) –

    The module identifier to deregister.

Returns:

  • bool

    True if module was removed, False if not found.

discover_by_id async ¤

discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

get_setup async ¤

get_setup(setup_id: str) -> None

Get setup info (not supported in default registry).

Parameters:

  • setup_id ¤
    (str) –

    The setup identifier.

get_status async ¤

get_status(module_id: str) -> ModuleStatusInfo

Get module status.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

heartbeat async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

register async ¤

register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: Updates existing module or creates new one in local storage.

Parameters:

  • module_id ¤
    (str) –

    Unique module identifier.

  • address ¤
    (str) –

    Network address.

  • port ¤
    (int) –

    Network port.

  • version ¤
    (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None otherwise.

search async ¤

search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤
    (str | None, default: None ) –

    Filter by name (partial match).

  • module_type ¤
    (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤
    (str | None, default: None ) –

    Filter by organization (not used in local storage).

Returns:

wait_for_ready async ¤

wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

DefaultSnapshot ¤


              flowchart TD
              digitalkin.services.DefaultSnapshot[DefaultSnapshot]
              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy --> digitalkin.services.DefaultSnapshot
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
                



              click digitalkin.services.DefaultSnapshot href "" "digitalkin.services.DefaultSnapshot"
              click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default snapshot strategy.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • create

    Create a new snapshot in the file system.

  • delete

    Delete snapshots from the file system.

  • get

    Get snapshots from the file system.

  • get_all

    Get all snapshots from the file system.

  • update

    Update snapshots in the file system.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

create ¤

create(data: dict[str, Any]) -> str

Create a new snapshot in the file system.

Returns:

  • str ( str ) –

    The ID of the new snapshot

delete ¤

delete(data: dict[str, Any]) -> int

Delete snapshots from the file system.

Returns:

  • int ( int ) –

    The number of snapshots deleted

get ¤

get(data: dict[str, Any]) -> None

Get snapshots from the file system.

get_all ¤

get_all() -> None

Get all snapshots from the file system.

update ¤

update(data: dict[str, Any]) -> int

Update snapshots in the file system.

Returns:

  • int ( int ) –

    The number of snapshots updated

DefaultStorage ¤

DefaultStorage(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
    storage_file_path: str = "local_storage",
)

              flowchart TD
              digitalkin.services.DefaultStorage[DefaultStorage]
              digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.DefaultStorage
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
                



              click digitalkin.services.DefaultStorage href "" "digitalkin.services.DefaultStorage"
              click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Persist records in a local JSON file for quick local development.

a JSON object of

{ ":": { ... StorageRecord fields ... },

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • list

    Get all records in a collection under the given scope.

  • read

    Get a record by key under the given scope.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

list async ¤

list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

read async ¤

read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name to retrieve data for

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

remove async ¤

remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤

remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤

store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str | None) –

    The unique ID for the record (optional)

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤

update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • data ¤
    (dict[str, Any]) –

    The new data to store

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤

upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID for the record

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

FilesystemStrategy ¤

FilesystemStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.FilesystemStrategy
                


              click digitalkin.services.FilesystemStrategy href "" "digitalkin.services.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for filesystem strategies.

This strategy provides comprehensive file management capabilities including upload, retrieval, update, and deletion operations with rich metadata support, filtering, and pagination.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

  • config ¤

    (dict[str, Any] | None, default: None ) –

    Configuration for the filesystem strategy

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • delete_files

    Delete multiple files.

  • get_file

    Get a specific file by ID or name.

  • get_files

    Get multiple files by various criteria.

  • update_file

    Update file metadata, content, or both.

  • upload_files

    Upload multiple files to the system.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

delete_files abstractmethod async ¤

delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files.

This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • permanent ¤
    (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤
    (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

get_file abstractmethod async ¤

get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a specific file by ID or name.

This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be retrieved

  • context ¤
    (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

  • FilesystemRecord

    tuple[FilesystemRecord, bytes | None]: Metadata about the retrieved file and optional content

get_files abstractmethod async ¤

get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

Get multiple files by various criteria.

This method provides efficient retrieval of multiple files using: - File IDs - File names - Path prefix With support for: - Pagination for large result sets - Optional content inclusion - Total count of matching files

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • list_size ¤
    (int, default: 100 ) –

    Number of files to return per page

  • offset ¤
    (int, default: 0 ) –

    Offset to start listing files from

  • order ¤
    (str | None, default: None ) –

    Field to order results by

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

update_file abstractmethod async ¤

update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update file metadata, content, or both.

This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be updated

  • content ¤
    (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤
    (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤
    (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤
    (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤
    (str | None, default: None ) –

    Optional new name for the file

  • status ¤
    (str | None, default: None ) –

    Optional new status for the file

Returns:

upload_files abstractmethod async ¤

Upload multiple files to the system.

This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.

Parameters:

  • files ¤
    (list[UploadFileData]) –

    List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)

Returns:

GrpcCommunication ¤


              flowchart TD
              digitalkin.services.GrpcCommunication[GrpcCommunication]
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]

                              digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.GrpcCommunication
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.GrpcCommunication
                


              click digitalkin.services.GrpcCommunication href "" "digitalkin.services.GrpcCommunication"
              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
            

gRPC client for module-to-module communication.

This class provides methods to communicate with remote modules using the Module Service gRPC protocol.

Parameters:

  • mission_id ¤

    (str) –

    Mission identifier

  • setup_id ¤

    (str) –

    Setup identifier

  • setup_version_id ¤

    (str) –

    Setup version identifier

  • client_config ¤

    (ClientConfig) –

    Client configuration for gRPC connection

Methods:

call_module async ¤

call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call a module and stream responses via gRPC.

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • input_data ¤
    (dict) –

    Input data as dictionary

  • setup_id ¤
    (str) –

    Setup configuration ID

  • mission_id ¤
    (str) –

    Mission context ID

  • callback ¤
    (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback for each response

  • metadata ¤
    (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers) to send with the request.

Yields:

close async ¤

close() -> None

Release all pooled gRPC channels.

close_all_cached_channels async classmethod ¤

close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_all_channels async ¤

close_all_channels() -> None

Release refs on all pooled gRPC channels.

close_channel async ¤

close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤

exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_module_schemas async ¤

get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas via gRPC.

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • llm_format ¤
    (bool, default: False ) –

    Return LLM-friendly format

Returns:

  • dict[str, dict]

    Dictionary containing schemas: input, output, setup, secret, cost

poll_grpc async ¤

poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤

release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

wait_for_ready async ¤

wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

IdentityStrategy ¤

IdentityStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.IdentityStrategy[IdentityStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.IdentityStrategy
                


              click digitalkin.services.IdentityStrategy href "" "digitalkin.services.IdentityStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

IdentityStrategy is the abstract base class for all identity strategies.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_identity

    Get the identity.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

get_identity abstractmethod async ¤

get_identity() -> str

Get the identity.

RegistryStrategy ¤

RegistryStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.RegistryStrategy
                


              click digitalkin.services.RegistryStrategy href "" "digitalkin.services.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for registry strategies.

Defines the interface for registry operations including module discovery, registration, and status management.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • get_setup

    Get setup info.

  • get_status

    Get module status.

  • heartbeat

    Send heartbeat to keep module active.

  • register

    Register a module with the registry.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

deregister abstractmethod async ¤

deregister(module_id: str) -> bool

Deregister a module from the registry.

Parameters:

  • module_id ¤
    (str) –

    The module identifier to deregister.

Returns:

  • bool

    True if deregistration was successful, False otherwise.

discover_by_id abstractmethod async ¤

discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

get_setup abstractmethod async ¤

get_setup(setup_id: str) -> SetupInfo | None

Get setup info.

get_status abstractmethod async ¤

get_status(module_id: str) -> ModuleStatusInfo

Get module status.

heartbeat abstractmethod async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

register abstractmethod async ¤

register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.

Parameters:

  • module_id ¤
    (str) –

    Unique module identifier.

  • address ¤
    (str) –

    Network address.

  • port ¤
    (int) –

    Network port.

  • version ¤
    (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None otherwise.

search abstractmethod async ¤

search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤
    (str | None, default: None ) –

    Filter by name (partial match via query).

  • module_type ¤
    (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤
    (str | None, default: None ) –

    Filter by organization.

Returns:

wait_for_ready async ¤

wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

SnapshotStrategy ¤

SnapshotStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.SnapshotStrategy[SnapshotStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.SnapshotStrategy
                


              click digitalkin.services.SnapshotStrategy href "" "digitalkin.services.SnapshotStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for snapshot strategies.

Parameters:

  • mission_id ¤

    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤

    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤

    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • create

    Create a new snapshot in the file system.

  • delete

    Delete snapshots from the file system.

  • get

    Get snapshots from the file system.

  • get_all

    Get all snapshots from the file system.

  • update

    Update snapshots in the file system.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

create abstractmethod ¤

create(data: dict[str, Any]) -> str

Create a new snapshot in the file system.

delete abstractmethod ¤

delete(data: dict[str, Any]) -> int

Delete snapshots from the file system.

get abstractmethod ¤

get(data: dict[str, Any]) -> None

Get snapshots from the file system.

get_all abstractmethod ¤

get_all() -> None

Get all snapshots from the file system.

update abstractmethod ¤

update(data: dict[str, Any]) -> int

Update snapshots in the file system.

StorageStrategy ¤

StorageStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
)

              flowchart TD
              digitalkin.services.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.StorageStrategy
                


              click digitalkin.services.StorageStrategy href "" "digitalkin.services.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Define CRUD + list/remove-collection against a collection/record store.

Records are scoped by a context string (the proto field), which is either self.mission_id (mission scope, the default) or self.setup_version_id (setup-version scope). Both attributes are expected to already contain the full prefix (missions:<id> / setup_versions:<id>).

Public methods accept scope: Literal["mission", "setup"] (default "mission"); internally we resolve it to the matching context string and pass that to the abstract _store/_read/_update/_remove/_list/_remove_collection.

Parameters:

  • mission_id ¤

    (str) –

    Already-prefixed mission context (missions:<id>).

  • setup_id ¤

    (str) –

    The ID of the setup

  • setup_version_id ¤

    (str) –

    Already-prefixed setup-version context (setup_versions:<id>).

  • config ¤

    (dict[str, type[BaseModel]]) –

    A dictionary mapping names to Pydantic model classes

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • list

    Get all records in a collection under the given scope.

  • read

    Get a record by key under the given scope.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

close async ¤

close() -> None

Release resources held by this strategy. No-op by default.

list async ¤

list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

read async ¤

read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name to retrieve data for

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

remove async ¤

remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤

remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤

store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str | None) –

    The unique ID for the record (optional)

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤

update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • data ¤
    (dict[str, Any]) –

    The new data to store

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤

upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID for the record

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

agent ¤

This module is responsible for handling the agent services.

Modules:

  • agent_strategy

    This module contains the abstract base class for agent strategies.

  • default_agent

    Default agent implementation for the agent service.

Classes:

  • AgentStrategy

    Abstract base class for agent strategies.

  • DefaultAgent

    Default agent implementation for the agent service.

AgentStrategy ¤


              flowchart TD
              digitalkin.services.agent.AgentStrategy[AgentStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.AgentStrategy
                


              click digitalkin.services.agent.AgentStrategy href "" "digitalkin.services.agent.AgentStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for agent strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • start

    Start the agent.

  • stop

    Stop the agent.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

start abstractmethod ¤
start() -> None

Start the agent.

stop abstractmethod ¤
stop() -> None

Stop the agent.

DefaultAgent ¤


              flowchart TD
              digitalkin.services.agent.DefaultAgent[DefaultAgent]
              digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.agent.agent_strategy.AgentStrategy --> digitalkin.services.agent.DefaultAgent
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
                



              click digitalkin.services.agent.DefaultAgent href "" "digitalkin.services.agent.DefaultAgent"
              click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default agent implementation for the agent service.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • start

    Start the agent.

  • stop

    Stop the agent.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

start ¤
start() -> None

Start the agent.

stop ¤
stop() -> None

Stop the agent.

agent_strategy ¤

This module contains the abstract base class for agent strategies.

Classes:

AgentStrategy ¤

              flowchart TD
              digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
                


              click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for agent strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • start

    Start the agent.

  • stop

    Stop the agent.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

start abstractmethod ¤
start() -> None

Start the agent.

stop abstractmethod ¤
stop() -> None

Stop the agent.

default_agent ¤

Default agent implementation for the agent service.

Classes:

  • DefaultAgent

    Default agent implementation for the agent service.

DefaultAgent ¤

              flowchart TD
              digitalkin.services.agent.default_agent.DefaultAgent[DefaultAgent]
              digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.agent.agent_strategy.AgentStrategy --> digitalkin.services.agent.default_agent.DefaultAgent
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
                



              click digitalkin.services.agent.default_agent.DefaultAgent href "" "digitalkin.services.agent.default_agent.DefaultAgent"
              click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default agent implementation for the agent service.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • start

    Start the agent.

  • stop

    Stop the agent.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

start ¤
start() -> None

Start the agent.

stop ¤
stop() -> None

Stop the agent.

base_strategy ¤

This module contains the abstract base class for storage strategies.

Classes:

BaseStrategy ¤


              flowchart TD
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

              

              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for all strategies.

This class defines the interface for all strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

communication ¤

Communication service for module-to-module interaction.

Modules:

Classes:

CommunicationStrategy ¤

CommunicationStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.communication.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.CommunicationStrategy
                


              click digitalkin.services.communication.CommunicationStrategy href "" "digitalkin.services.communication.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for module-to-module communication.

This service enables: - Archetype → Tool communication - Archetype → Archetype communication - Tool → Tool communication - Any module → Any module communication

The service wraps the Module Service protocol from agentic-mesh-protocol.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • call_module

    Call a module and stream responses.

  • close

    Release communication resources (channels, connection pools).

  • get_module_schemas

    Get module schemas (input/output/setup/secret/cost).

call_module abstractmethod async ¤
call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call a module and stream responses.

Uses Module Service StartModule RPC to execute the module. Streams responses as they are generated by the module.

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • input_data ¤
    (dict) –

    Input data as dictionary

  • setup_id ¤
    (str) –

    Setup configuration ID

  • mission_id ¤
    (str) –

    Mission context ID

  • callback ¤
    (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback for each response

  • metadata ¤
    (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers) to send with the request.

Yields:

close abstractmethod async ¤
close() -> None

Release communication resources (channels, connection pools).

get_module_schemas abstractmethod async ¤
get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas (input/output/setup/secret/cost).

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • llm_format ¤
    (bool, default: False ) –

    Return LLM-friendly format (simplified schema). Note: cost always returns actual data regardless of this flag.

Returns:

  • dict[str, dict]

    Dictionary containing schemas:

  • dict[str, dict]

    { "input": {...}, "output": {...}, "setup": {...}, "secret": {...}, "cost": {...}

  • dict[str, dict]

    }

DefaultCommunication ¤

DefaultCommunication(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.communication.DefaultCommunication[DefaultCommunication]
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.DefaultCommunication
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                



              click digitalkin.services.communication.DefaultCommunication href "" "digitalkin.services.communication.DefaultCommunication"
              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default communication strategy (local implementation).

This implementation is primarily for testing and development. For production, use GrpcCommunication to connect to remote modules.

Parameters:

  • mission_id ¤
    (str) –

    Mission identifier

  • setup_id ¤
    (str) –

    Setup identifier

  • setup_version_id ¤
    (str) –

    Setup version identifier

Methods:

  • call_module

    Call module (local implementation yields empty response).

  • close

    No-op for local communication.

  • get_module_schemas

    Get module schemas (local implementation returns empty schemas).

call_module async ¤
call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call module (local implementation yields empty response).

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • input_data ¤
    (dict) –

    Input data

  • setup_id ¤
    (str) –

    Setup ID

  • mission_id ¤
    (str) –

    Mission ID

  • callback ¤
    (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback

  • metadata ¤
    (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers).

Yields:

close async ¤
close() -> None

No-op for local communication.

get_module_schemas async ¤
get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas (local implementation returns empty schemas).

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • llm_format ¤
    (bool, default: False ) –

    Return LLM-friendly format

Returns:

GrpcCommunication ¤


              flowchart TD
              digitalkin.services.communication.GrpcCommunication[GrpcCommunication]
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]

                              digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.GrpcCommunication
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.communication.GrpcCommunication
                


              click digitalkin.services.communication.GrpcCommunication href "" "digitalkin.services.communication.GrpcCommunication"
              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
            

gRPC client for module-to-module communication.

This class provides methods to communicate with remote modules using the Module Service gRPC protocol.

Parameters:

  • mission_id ¤
    (str) –

    Mission identifier

  • setup_id ¤
    (str) –

    Setup identifier

  • setup_version_id ¤
    (str) –

    Setup version identifier

  • client_config ¤
    (ClientConfig) –

    Client configuration for gRPC connection

Methods:

call_module async ¤
call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call a module and stream responses via gRPC.

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • input_data ¤
    (dict) –

    Input data as dictionary

  • setup_id ¤
    (str) –

    Setup configuration ID

  • mission_id ¤
    (str) –

    Mission context ID

  • callback ¤
    (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback for each response

  • metadata ¤
    (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers) to send with the request.

Yields:

close async ¤
close() -> None

Release all pooled gRPC channels.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_all_channels async ¤
close_all_channels() -> None

Release refs on all pooled gRPC channels.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_module_schemas async ¤
get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas via gRPC.

Parameters:

  • module_address ¤
    (str) –

    Target module address

  • module_port ¤
    (int) –

    Target module port

  • llm_format ¤
    (bool, default: False ) –

    Return LLM-friendly format

Returns:

  • dict[str, dict]

    Dictionary containing schemas: input, output, setup, secret, cost

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

communication_strategy ¤

Abstract base class for communication strategies.

Classes:

CommunicationStrategy ¤
CommunicationStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                


              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for module-to-module communication.

This service enables: - Archetype → Tool communication - Archetype → Archetype communication - Tool → Tool communication - Any module → Any module communication

The service wraps the Module Service protocol from agentic-mesh-protocol.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • call_module

    Call a module and stream responses.

  • close

    Release communication resources (channels, connection pools).

  • get_module_schemas

    Get module schemas (input/output/setup/secret/cost).

call_module abstractmethod async ¤
call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call a module and stream responses.

Uses Module Service StartModule RPC to execute the module. Streams responses as they are generated by the module.

Parameters:

  • module_address ¤ (str) –

    Target module address

  • module_port ¤ (int) –

    Target module port

  • input_data ¤ (dict) –

    Input data as dictionary

  • setup_id ¤ (str) –

    Setup configuration ID

  • mission_id ¤ (str) –

    Mission context ID

  • callback ¤ (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback for each response

  • metadata ¤ (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers) to send with the request.

Yields:

close abstractmethod async ¤
close() -> None

Release communication resources (channels, connection pools).

get_module_schemas abstractmethod async ¤
get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas (input/output/setup/secret/cost).

Parameters:

  • module_address ¤ (str) –

    Target module address

  • module_port ¤ (int) –

    Target module port

  • llm_format ¤ (bool, default: False ) –

    Return LLM-friendly format (simplified schema). Note: cost always returns actual data regardless of this flag.

Returns:

  • dict[str, dict]

    Dictionary containing schemas:

  • dict[str, dict]

    { "input": {...}, "output": {...}, "setup": {...}, "secret": {...}, "cost": {...}

  • dict[str, dict]

    }

default_communication ¤

Default communication implementation (local, for testing).

Classes:

DefaultCommunication ¤
DefaultCommunication(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.communication.default_communication.DefaultCommunication[DefaultCommunication]
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.default_communication.DefaultCommunication
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                



              click digitalkin.services.communication.default_communication.DefaultCommunication href "" "digitalkin.services.communication.default_communication.DefaultCommunication"
              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default communication strategy (local implementation).

This implementation is primarily for testing and development. For production, use GrpcCommunication to connect to remote modules.

Parameters:

  • mission_id ¤
    (str) –

    Mission identifier

  • setup_id ¤
    (str) –

    Setup identifier

  • setup_version_id ¤
    (str) –

    Setup version identifier

Methods:

  • call_module

    Call module (local implementation yields empty response).

  • close

    No-op for local communication.

  • get_module_schemas

    Get module schemas (local implementation returns empty schemas).

call_module async ¤
call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call module (local implementation yields empty response).

Parameters:

  • module_address ¤ (str) –

    Target module address

  • module_port ¤ (int) –

    Target module port

  • input_data ¤ (dict) –

    Input data

  • setup_id ¤ (str) –

    Setup ID

  • mission_id ¤ (str) –

    Mission ID

  • callback ¤ (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback

  • metadata ¤ (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers).

Yields:

close async ¤
close() -> None

No-op for local communication.

get_module_schemas async ¤
get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas (local implementation returns empty schemas).

Parameters:

  • module_address ¤ (str) –

    Target module address

  • module_port ¤ (int) –

    Target module port

  • llm_format ¤ (bool, default: False ) –

    Return LLM-friendly format

Returns:

grpc_communication ¤

gRPC client implementation for Communication service.

Classes:

GrpcCommunication ¤

              flowchart TD
              digitalkin.services.communication.grpc_communication.GrpcCommunication[GrpcCommunication]
              digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]

                              digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.grpc_communication.GrpcCommunication
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.communication.grpc_communication.GrpcCommunication
                


              click digitalkin.services.communication.grpc_communication.GrpcCommunication href "" "digitalkin.services.communication.grpc_communication.GrpcCommunication"
              click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
            

gRPC client for module-to-module communication.

This class provides methods to communicate with remote modules using the Module Service gRPC protocol.

Parameters:

  • mission_id ¤
    (str) –

    Mission identifier

  • setup_id ¤
    (str) –

    Setup identifier

  • setup_version_id ¤
    (str) –

    Setup version identifier

  • client_config ¤
    (ClientConfig) –

    Client configuration for gRPC connection

Methods:

call_module async ¤
call_module(
    module_address: str,
    module_port: int,
    input_data: dict,
    setup_id: str,
    mission_id: str,
    callback: Callable[[dict], Awaitable[None]] | None = None,
    metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]

Call a module and stream responses via gRPC.

Parameters:

  • module_address ¤ (str) –

    Target module address

  • module_port ¤ (int) –

    Target module port

  • input_data ¤ (dict) –

    Input data as dictionary

  • setup_id ¤ (str) –

    Setup configuration ID

  • mission_id ¤ (str) –

    Mission context ID

  • callback ¤ (Callable[[dict], Awaitable[None]] | None, default: None ) –

    Optional callback for each response

  • metadata ¤ (dict[str, str] | None, default: None ) –

    Optional gRPC metadata (headers) to send with the request.

Yields:

close async ¤
close() -> None

Release all pooled gRPC channels.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_all_channels async ¤
close_all_channels() -> None

Release refs on all pooled gRPC channels.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_module_schemas async ¤
get_module_schemas(
    module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]

Get module schemas via gRPC.

Parameters:

  • module_address ¤ (str) –

    Target module address

  • module_port ¤ (int) –

    Target module port

  • llm_format ¤ (bool, default: False ) –

    Return LLM-friendly format

Returns:

  • dict[str, dict]

    Dictionary containing schemas: input, output, setup, secret, cost

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

cost ¤

This module is responsible for handling the cost services.

Modules:

  • cost_strategy

    This module contains the abstract base class for cost strategies.

  • default_cost

    Default cost.

  • grpc_cost

    This module implements the gRPC Cost strategy.

Classes:

  • CostConfig

    Pydantic model that defines a cost configuration.

  • CostData

    Data model for cost operations.

  • CostStrategy

    Abstract base class for cost strategies.

  • CostType

    Enum defining the types of costs that can be registered.

  • DefaultCost

    Default cost strategy.

  • GrpcCost

    gRPC client implementation for the Cost service.

CostConfig ¤


              flowchart TD
              digitalkin.services.cost.CostConfig[CostConfig]

              

              click digitalkin.services.cost.CostConfig href "" "digitalkin.services.cost.CostConfig"
            

Pydantic model that defines a cost configuration.

:param cost_name: Name of the cost (unique identifier in the service). :param cost_type: The type/category of the cost. :param description: A short description of the cost. :param unit: The unit of measurement (e.g. token, call, MB). :param rate: The cost per unit (e.g. dollars per token).

CostData ¤


              flowchart TD
              digitalkin.services.cost.CostData[CostData]

              

              click digitalkin.services.cost.CostData href "" "digitalkin.services.cost.CostData"
            

Data model for cost operations.

CostStrategy ¤


              flowchart TD
              digitalkin.services.cost.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.CostStrategy
                


              click digitalkin.services.cost.CostStrategy href "" "digitalkin.services.cost.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for cost strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • add

    Register a new cost.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • get

    Get a cost.

  • get_cost_config

    Get cost configuration for the current setup version.

  • get_filtered

    Get filtered costs.

  • set_cost_config

    Store cost configuration for the current setup version.

  • set_limits

    Set cost limits for this session.

add abstractmethod async ¤
add(name: str, cost_config_name: str, quantity: float) -> None

Register a new cost.

check_limit abstractmethod async ¤
check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤
    (str) –

    Name of the cost config.

  • quantity ¤
    (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get abstractmethod async ¤
get(name: str) -> list[CostData]

Get a cost.

get_cost_config abstractmethod async ¤
get_cost_config() -> list[CostConfig]

Get cost configuration for the current setup version.

Returns:

get_filtered abstractmethod async ¤
get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered costs.

set_cost_config abstractmethod async ¤
set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration for the current setup version.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits abstractmethod async ¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

CostType ¤


              flowchart TD
              digitalkin.services.cost.CostType[CostType]

              

              click digitalkin.services.cost.CostType href "" "digitalkin.services.cost.CostType"
            

Enum defining the types of costs that can be registered.

DefaultCost ¤


              flowchart TD
              digitalkin.services.cost.DefaultCost[DefaultCost]
              digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.DefaultCost
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
                



              click digitalkin.services.cost.DefaultCost href "" "digitalkin.services.cost.DefaultCost"
              click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default cost strategy.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

  • config ¤
    (dict[str, CostConfig]) –

    The configuration dictionary for the cost

Methods:

  • add

    Create a new record in the cost database.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • get

    Get a record from the database.

  • get_cost_config

    Get cost configuration from in-memory config.

  • get_filtered

    Get records from the database.

  • set_cost_config

    Store cost configuration in memory.

  • set_limits

    Set cost limits for this session.

add async ¤

Create a new record in the cost database.

Parameters:

  • name ¤
    (str) –

    The name of the cost

  • cost_config_name ¤
    (str) –

    The name of the cost config

  • quantity ¤
    (float) –

    The quantity of the cost

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost already exists

check_limit async ¤
check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤
    (str) –

    Name of the cost config.

  • quantity ¤
    (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get async ¤
get(name: str) -> list[CostData]

Get a record from the database.

Parameters:

  • name ¤
    (str) –

    The name of the cost

Returns:

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost does not exist

get_cost_config async ¤
get_cost_config() -> list[CostConfig]

Get cost configuration from in-memory config.

Returns:

  • list[CostConfig]

    List of CostConfig objects from the config dictionary.

get_filtered async ¤
get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get records from the database.

Parameters:

  • names ¤
    (list[str] | None, default: None ) –

    The names of the costs

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    The types of the costs

Returns:

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost does not exist

set_cost_config async ¤
set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration in memory.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits async ¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

GrpcCost ¤

GrpcCost(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, CostConfig],
    client_config: ClientConfig,
)

              flowchart TD
              digitalkin.services.cost.GrpcCost[GrpcCost]
              digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.GrpcCost
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.cost.GrpcCost
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.cost.GrpcCost
                


              click digitalkin.services.cost.GrpcCost href "" "digitalkin.services.cost.GrpcCost"
              click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC client implementation for the Cost service.

Methods:

  • add

    Create a new record in the cost database.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get

    Get a record from the database.

  • get_cost_config

    Get cost configuration from the database.

  • get_filtered

    Get a list of records from the database.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • set_cost_config

    Store cost configuration in the database.

  • set_limits

    Set cost limits for this session.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

add async ¤

Create a new record in the cost database.

Parameters:

  • name ¤
    (str) –

    The name of the cost

  • cost_config_name ¤
    (str) –

    The name of the cost config

  • quantity ¤
    (float) –

    The quantity of the cost

Raises:

check_limit async ¤
check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤
    (str) –

    Name of the cost config.

  • quantity ¤
    (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get async ¤
get(name: str) -> list[CostData]

Get a record from the database.

Parameters:

  • name ¤
    (str) –

    The name of the cost

Returns:

get_cost_config async ¤
get_cost_config() -> list[CostConfig]

Get cost configuration from the database.

Returns:

get_filtered async ¤
get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get a list of records from the database.

Parameters:

  • names ¤
    (list[str] | None, default: None ) –

    The names of the costs

  • cost_types ¤
    (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    The types of the costs

Returns:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤
    (str) –

    Name of the operation being performed.

  • service_error_class ¤
    (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

set_cost_config async ¤
set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration in the database.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits async ¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

cost_strategy ¤

This module contains the abstract base class for cost strategies.

Classes:

  • CostConfig

    Pydantic model that defines a cost configuration.

  • CostData

    Data model for cost operations.

  • CostServiceError

    Custom exception for CostService errors.

  • CostStrategy

    Abstract base class for cost strategies.

  • CostType

    Enum defining the types of costs that can be registered.

CostConfig ¤

              flowchart TD
              digitalkin.services.cost.cost_strategy.CostConfig[CostConfig]

              

              click digitalkin.services.cost.cost_strategy.CostConfig href "" "digitalkin.services.cost.cost_strategy.CostConfig"
            

Pydantic model that defines a cost configuration.

:param cost_name: Name of the cost (unique identifier in the service). :param cost_type: The type/category of the cost. :param description: A short description of the cost. :param unit: The unit of measurement (e.g. token, call, MB). :param rate: The cost per unit (e.g. dollars per token).

CostData ¤

              flowchart TD
              digitalkin.services.cost.cost_strategy.CostData[CostData]

              

              click digitalkin.services.cost.cost_strategy.CostData href "" "digitalkin.services.cost.cost_strategy.CostData"
            

Data model for cost operations.

CostServiceError ¤

              flowchart TD
              digitalkin.services.cost.cost_strategy.CostServiceError[CostServiceError]

              

              click digitalkin.services.cost.cost_strategy.CostServiceError href "" "digitalkin.services.cost.cost_strategy.CostServiceError"
            

Custom exception for CostService errors.

CostStrategy ¤

              flowchart TD
              digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
                


              click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for cost strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • add

    Register a new cost.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • get

    Get a cost.

  • get_cost_config

    Get cost configuration for the current setup version.

  • get_filtered

    Get filtered costs.

  • set_cost_config

    Store cost configuration for the current setup version.

  • set_limits

    Set cost limits for this session.

add abstractmethod async ¤
add(name: str, cost_config_name: str, quantity: float) -> None

Register a new cost.

check_limit abstractmethod async ¤
check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤ (str) –

    Name of the cost config.

  • quantity ¤ (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get abstractmethod async ¤
get(name: str) -> list[CostData]

Get a cost.

get_cost_config abstractmethod async ¤
get_cost_config() -> list[CostConfig]

Get cost configuration for the current setup version.

Returns:

get_filtered abstractmethod async ¤
get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get filtered costs.

set_cost_config abstractmethod async ¤
set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration for the current setup version.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits abstractmethod async ¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

CostType ¤

              flowchart TD
              digitalkin.services.cost.cost_strategy.CostType[CostType]

              

              click digitalkin.services.cost.cost_strategy.CostType href "" "digitalkin.services.cost.cost_strategy.CostType"
            

Enum defining the types of costs that can be registered.

default_cost ¤

Default cost.

Classes:

DefaultCost ¤

              flowchart TD
              digitalkin.services.cost.default_cost.DefaultCost[DefaultCost]
              digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.default_cost.DefaultCost
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
                



              click digitalkin.services.cost.default_cost.DefaultCost href "" "digitalkin.services.cost.default_cost.DefaultCost"
              click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default cost strategy.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

  • config ¤
    (dict[str, CostConfig]) –

    The configuration dictionary for the cost

Methods:

  • add

    Create a new record in the cost database.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • get

    Get a record from the database.

  • get_cost_config

    Get cost configuration from in-memory config.

  • get_filtered

    Get records from the database.

  • set_cost_config

    Store cost configuration in memory.

  • set_limits

    Set cost limits for this session.

add async ¤

Create a new record in the cost database.

Parameters:

  • name ¤ (str) –

    The name of the cost

  • cost_config_name ¤ (str) –

    The name of the cost config

  • quantity ¤ (float) –

    The quantity of the cost

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost already exists

check_limit async ¤
check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤ (str) –

    Name of the cost config.

  • quantity ¤ (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get async ¤
get(name: str) -> list[CostData]

Get a record from the database.

Parameters:

  • name ¤ (str) –

    The name of the cost

Returns:

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost does not exist

get_cost_config async ¤
get_cost_config() -> list[CostConfig]

Get cost configuration from in-memory config.

Returns:

  • list[CostConfig]

    List of CostConfig objects from the config dictionary.

get_filtered async ¤
get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get records from the database.

Parameters:

  • names ¤ (list[str] | None, default: None ) –

    The names of the costs

  • cost_types ¤ (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    The types of the costs

Returns:

Raises:

  • CostServiceError

    If the cost data is invalid or if the cost does not exist

set_cost_config async ¤
set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration in memory.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits async ¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

grpc_cost ¤

This module implements the gRPC Cost strategy.

Classes:

  • GrpcCost

    gRPC client implementation for the Cost service.

GrpcCost ¤
GrpcCost(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, CostConfig],
    client_config: ClientConfig,
)

              flowchart TD
              digitalkin.services.cost.grpc_cost.GrpcCost[GrpcCost]
              digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.grpc_cost.GrpcCost
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.cost.grpc_cost.GrpcCost
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.cost.grpc_cost.GrpcCost
                


              click digitalkin.services.cost.grpc_cost.GrpcCost href "" "digitalkin.services.cost.grpc_cost.GrpcCost"
              click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC client implementation for the Cost service.

Methods:

  • add

    Create a new record in the cost database.

  • check_limit

    Check if adding this cost would exceed any limits.

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get

    Get a record from the database.

  • get_cost_config

    Get cost configuration from the database.

  • get_filtered

    Get a list of records from the database.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • set_cost_config

    Store cost configuration in the database.

  • set_limits

    Set cost limits for this session.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

add async ¤

Create a new record in the cost database.

Parameters:

  • name ¤ (str) –

    The name of the cost

  • cost_config_name ¤ (str) –

    The name of the cost config

  • quantity ¤ (float) –

    The quantity of the cost

Raises:

check_limit async ¤
check_limit(cost_config_name: str, quantity: float) -> bool

Check if adding this cost would exceed any limits.

Parameters:

  • cost_config_name ¤ (str) –

    Name of the cost config.

  • quantity ¤ (float) –

    Quantity to add.

Returns:

  • bool

    True if within limits, False if would exceed.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get async ¤
get(name: str) -> list[CostData]

Get a record from the database.

Parameters:

  • name ¤ (str) –

    The name of the cost

Returns:

get_cost_config async ¤
get_cost_config() -> list[CostConfig]

Get cost configuration from the database.

Returns:

get_filtered async ¤
get_filtered(
    names: list[str] | None = None,
    cost_types: list[
        Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
    ]
    | None = None,
) -> list[CostData]

Get a list of records from the database.

Parameters:

  • names ¤ (list[str] | None, default: None ) –

    The names of the costs

  • cost_types ¤ (list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default: None ) –

    The types of the costs

Returns:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤ (str) –

    Name of the operation being performed.

  • service_error_class ¤ (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

set_cost_config async ¤
set_cost_config(configs: list[CostConfig]) -> bool

Store cost configuration in the database.

Parameters:

Returns:

  • bool

    True if successfully stored.

set_limits async ¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None

Set cost limits for this session.

Parameters:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

filesystem ¤

This module is responsible for handling the filesystem services.

Modules:

Classes:

DefaultFilesystem ¤

DefaultFilesystem(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.filesystem.DefaultFilesystem[DefaultFilesystem]
              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.DefaultFilesystem
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
                



              click digitalkin.services.filesystem.DefaultFilesystem href "" "digitalkin.services.filesystem.DefaultFilesystem"
              click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default filesystem implementation.

This implementation provides a local filesystem-based storage solution with support for all filesystem operations defined in the strategy. Files are stored in a temporary directory with proper metadata tracking.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • delete_files

    Delete multiple files.

  • get_file

    Get a specific file by ID or name.

  • get_files

    List files with filtering, sorting, and pagination.

  • update_file

    Update file metadata, content, or both.

  • upload_files

    Upload multiple files to the system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

delete_files async ¤
delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files.

This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files to delete

  • permanent ¤
    (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤
    (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

Raises:

get_file async ¤
get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a specific file by ID or name.

This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be retrieved

  • context ¤
    (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

get_files async ¤
get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

List files with filtering, sorting, and pagination.

This method provides flexible file querying capabilities with support for: - Multiple filter criteria (name, type, dates, size, etc.) - Pagination for large result sets - Sorting by various fields - Scoped access by context

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • list_size ¤
    (int, default: 100 ) –

    Number of files to return per page

  • offset ¤
    (int, default: 0 ) –

    Offset to start listing files from

  • order ¤
    (str | None, default: None ) –

    Fields to order results by (example: "created_at:asc,name:desc")

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

update_file async ¤
update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update file metadata, content, or both.

This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions

Parameters:

  • file_id ¤
    (str) –

    The id of the file to be updated

  • content ¤
    (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤
    (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤
    (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤
    (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤
    (str | None, default: None ) –

    Optional new name for the file

  • status ¤
    (str | None, default: None ) –

    Optional new status for the file

Returns:

Raises:

upload_files async ¤

Upload multiple files to the system.

This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.

Parameters:

Returns:

Raises:

FilesystemStrategy ¤

FilesystemStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.filesystem.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.FilesystemStrategy
                


              click digitalkin.services.filesystem.FilesystemStrategy href "" "digitalkin.services.filesystem.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for filesystem strategies.

This strategy provides comprehensive file management capabilities including upload, retrieval, update, and deletion operations with rich metadata support, filtering, and pagination.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

  • config ¤
    (dict[str, Any] | None, default: None ) –

    Configuration for the filesystem strategy

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • delete_files

    Delete multiple files.

  • get_file

    Get a specific file by ID or name.

  • get_files

    Get multiple files by various criteria.

  • update_file

    Update file metadata, content, or both.

  • upload_files

    Upload multiple files to the system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

delete_files abstractmethod async ¤
delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files.

This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • permanent ¤
    (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤
    (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

get_file abstractmethod async ¤
get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a specific file by ID or name.

This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be retrieved

  • context ¤
    (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

  • FilesystemRecord

    tuple[FilesystemRecord, bytes | None]: Metadata about the retrieved file and optional content

get_files abstractmethod async ¤
get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

Get multiple files by various criteria.

This method provides efficient retrieval of multiple files using: - File IDs - File names - Path prefix With support for: - Pagination for large result sets - Optional content inclusion - Total count of matching files

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • list_size ¤
    (int, default: 100 ) –

    Number of files to return per page

  • offset ¤
    (int, default: 0 ) –

    Offset to start listing files from

  • order ¤
    (str | None, default: None ) –

    Field to order results by

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

update_file abstractmethod async ¤
update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update file metadata, content, or both.

This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be updated

  • content ¤
    (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤
    (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤
    (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤
    (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤
    (str | None, default: None ) –

    Optional new name for the file

  • status ¤
    (str | None, default: None ) –

    Optional new status for the file

Returns:

upload_files abstractmethod async ¤

Upload multiple files to the system.

This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.

Parameters:

  • files ¤
    (list[UploadFileData]) –

    List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)

Returns:

GrpcFilesystem ¤

GrpcFilesystem(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    client_config: ClientConfig,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.filesystem.GrpcFilesystem[GrpcFilesystem]
              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.GrpcFilesystem
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.filesystem.GrpcFilesystem
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.filesystem.GrpcFilesystem
                


              click digitalkin.services.filesystem.GrpcFilesystem href "" "digitalkin.services.filesystem.GrpcFilesystem"
              click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC client implementation for the Filesystem service.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

  • client_config ¤
    (ClientConfig) –

    Configuration for the gRPC client connection

  • config ¤
    (dict[str, Any] | None, default: None ) –

    Configuration for the filesystem strategy

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • delete_files

    Delete multiple files from the filesystem.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get_file

    Get a file from the filesystem.

  • get_files

    Get multiple files from the filesystem.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • update_file

    Update a file in the filesystem.

  • upload_files

    Upload multiple files to the filesystem.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

delete_files async ¤
delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files from the filesystem.

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • permanent ¤
    (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤
    (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_file async ¤
get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a file from the filesystem.

Parameters:

  • file_id ¤
    (str) –

    The ID of the file to be retrieved

  • context ¤
    (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

get_files async ¤
get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

Get multiple files from the filesystem.

Parameters:

  • filters ¤
    (FileFilter) –

    Filter criteria for the files

  • list_size ¤
    (int, default: 100 ) –

    Number of files to return per page

  • offset ¤
    (int, default: 0 ) –

    Offset to start from

  • order ¤
    (str | None, default: None ) –

    Field to order results by

  • include_content ¤
    (bool, default: False ) –

    Whether to include file content in response

Returns:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤
    (str) –

    Name of the operation being performed.

  • service_error_class ¤
    (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

update_file async ¤
update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update a file in the filesystem.

Parameters:

  • file_id ¤
    (str) –

    The id of the file to be updated

  • content ¤
    (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤
    (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤
    (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤
    (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤
    (str | None, default: None ) –

    Optional new name for the file

  • status ¤
    (str | None, default: None ) –

    Optional new status for the file

Returns:

Raises:

upload_files async ¤

Upload multiple files to the filesystem.

Parameters:

  • files ¤
    (list[UploadFileData]) –

    List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)

Returns:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

default_filesystem ¤

Default filesystem implementation.

Classes:

DefaultFilesystem ¤
DefaultFilesystem(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.filesystem.default_filesystem.DefaultFilesystem[DefaultFilesystem]
              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.default_filesystem.DefaultFilesystem
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
                



              click digitalkin.services.filesystem.default_filesystem.DefaultFilesystem href "" "digitalkin.services.filesystem.default_filesystem.DefaultFilesystem"
              click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default filesystem implementation.

This implementation provides a local filesystem-based storage solution with support for all filesystem operations defined in the strategy. Files are stored in a temporary directory with proper metadata tracking.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • delete_files

    Delete multiple files.

  • get_file

    Get a specific file by ID or name.

  • get_files

    List files with filtering, sorting, and pagination.

  • update_file

    Update file metadata, content, or both.

  • upload_files

    Upload multiple files to the system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

delete_files async ¤
delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files.

This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file

Parameters:

  • filters ¤ (FileFilter) –

    Filter criteria for the files to delete

  • permanent ¤ (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤ (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

Raises:

get_file async ¤
get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a specific file by ID or name.

This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.

Parameters:

  • file_id ¤ (str) –

    The ID of the file to be retrieved

  • context ¤ (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤ (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

get_files async ¤
get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

List files with filtering, sorting, and pagination.

This method provides flexible file querying capabilities with support for: - Multiple filter criteria (name, type, dates, size, etc.) - Pagination for large result sets - Sorting by various fields - Scoped access by context

Parameters:

  • filters ¤ (FileFilter) –

    Filter criteria for the files

  • list_size ¤ (int, default: 100 ) –

    Number of files to return per page

  • offset ¤ (int, default: 0 ) –

    Offset to start listing files from

  • order ¤ (str | None, default: None ) –

    Fields to order results by (example: "created_at:asc,name:desc")

  • include_content ¤ (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

update_file async ¤
update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update file metadata, content, or both.

This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions

Parameters:

  • file_id ¤ (str) –

    The id of the file to be updated

  • content ¤ (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤ (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤ (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤ (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤ (str | None, default: None ) –

    Optional new name for the file

  • status ¤ (str | None, default: None ) –

    Optional new status for the file

Returns:

Raises:

upload_files async ¤

Upload multiple files to the system.

This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.

Parameters:

Returns:

Raises:

filesystem_strategy ¤

This module contains the abstract base class for filesystem strategies.

Classes:

FileFilter ¤

              flowchart TD
              digitalkin.services.filesystem.filesystem_strategy.FileFilter[FileFilter]

              

              click digitalkin.services.filesystem.filesystem_strategy.FileFilter href "" "digitalkin.services.filesystem.filesystem_strategy.FileFilter"
            

Filter criteria for querying files.

FilesystemRecord ¤

              flowchart TD
              digitalkin.services.filesystem.filesystem_strategy.FilesystemRecord[FilesystemRecord]

              

              click digitalkin.services.filesystem.filesystem_strategy.FilesystemRecord href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemRecord"
            

Data model for filesystem operations.

FilesystemServiceError ¤

              flowchart TD
              digitalkin.services.filesystem.filesystem_strategy.FilesystemServiceError[FilesystemServiceError]

              

              click digitalkin.services.filesystem.filesystem_strategy.FilesystemServiceError href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemServiceError"
            

Base exception for Filesystem service errors.

FilesystemStrategy ¤
FilesystemStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
                


              click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for filesystem strategies.

This strategy provides comprehensive file management capabilities including upload, retrieval, update, and deletion operations with rich metadata support, filtering, and pagination.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

  • config ¤
    (dict[str, Any] | None, default: None ) –

    Configuration for the filesystem strategy

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • delete_files

    Delete multiple files.

  • get_file

    Get a specific file by ID or name.

  • get_files

    Get multiple files by various criteria.

  • update_file

    Update file metadata, content, or both.

  • upload_files

    Upload multiple files to the system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

delete_files abstractmethod async ¤
delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files.

This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file

Parameters:

  • filters ¤ (FileFilter) –

    Filter criteria for the files

  • permanent ¤ (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤ (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

get_file abstractmethod async ¤
get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a specific file by ID or name.

This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.

Parameters:

  • file_id ¤ (str) –

    The ID of the file to be retrieved

  • context ¤ (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤ (bool, default: False ) –

    Whether to include file content in response

Returns:

  • FilesystemRecord

    tuple[FilesystemRecord, bytes | None]: Metadata about the retrieved file and optional content

get_files abstractmethod async ¤
get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

Get multiple files by various criteria.

This method provides efficient retrieval of multiple files using: - File IDs - File names - Path prefix With support for: - Pagination for large result sets - Optional content inclusion - Total count of matching files

Parameters:

  • filters ¤ (FileFilter) –

    Filter criteria for the files

  • list_size ¤ (int, default: 100 ) –

    Number of files to return per page

  • offset ¤ (int, default: 0 ) –

    Offset to start listing files from

  • order ¤ (str | None, default: None ) –

    Field to order results by

  • include_content ¤ (bool, default: False ) –

    Whether to include file content in response

Returns:

update_file abstractmethod async ¤
update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update file metadata, content, or both.

This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions

Parameters:

  • file_id ¤ (str) –

    The ID of the file to be updated

  • content ¤ (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤ (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤ (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤ (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤ (str | None, default: None ) –

    Optional new name for the file

  • status ¤ (str | None, default: None ) –

    Optional new status for the file

Returns:

upload_files abstractmethod async ¤

Upload multiple files to the system.

This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.

Parameters:

  • files ¤ (list[UploadFileData]) –

    List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)

Returns:

UploadFileData ¤

              flowchart TD
              digitalkin.services.filesystem.filesystem_strategy.UploadFileData[UploadFileData]

              

              click digitalkin.services.filesystem.filesystem_strategy.UploadFileData href "" "digitalkin.services.filesystem.filesystem_strategy.UploadFileData"
            

Data model for uploading a file.

grpc_filesystem ¤

gRPC filesystem implementation.

Classes:

  • GrpcFilesystem

    gRPC client implementation for the Filesystem service.

GrpcFilesystem ¤
GrpcFilesystem(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    client_config: ClientConfig,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem[GrpcFilesystem]
              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem
                


              click digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem href "" "digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem"
              click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC client implementation for the Filesystem service.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

  • client_config ¤
    (ClientConfig) –

    Configuration for the gRPC client connection

  • config ¤
    (dict[str, Any] | None, default: None ) –

    Configuration for the filesystem strategy

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • delete_files

    Delete multiple files from the filesystem.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get_file

    Get a file from the filesystem.

  • get_files

    Get multiple files from the filesystem.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • update_file

    Update a file in the filesystem.

  • upload_files

    Upload multiple files to the filesystem.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

delete_files async ¤
delete_files(
    filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]

Delete multiple files from the filesystem.

Parameters:

  • filters ¤ (FileFilter) –

    Filter criteria for the files

  • permanent ¤ (bool, default: False ) –

    Whether to permanently delete the files

  • force ¤ (bool, default: False ) –

    Whether to force delete even if files are in use

Returns:

  • tuple[dict[str, bool], int, int]

    tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_file async ¤
get_file(
    file_id: str,
    context: Literal["mission", "setup"] = "mission",
    *,
    include_content: bool = False,
) -> FilesystemRecord

Get a file from the filesystem.

Parameters:

  • file_id ¤ (str) –

    The ID of the file to be retrieved

  • context ¤ (Literal['mission', 'setup'], default: 'mission' ) –

    The context of the files (mission or setup)

  • include_content ¤ (bool, default: False ) –

    Whether to include file content in response

Returns:

Raises:

get_files async ¤
get_files(
    filters: FileFilter,
    *,
    list_size: int = 100,
    offset: int = 0,
    order: str | None = None,
    include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]

Get multiple files from the filesystem.

Parameters:

  • filters ¤ (FileFilter) –

    Filter criteria for the files

  • list_size ¤ (int, default: 100 ) –

    Number of files to return per page

  • offset ¤ (int, default: 0 ) –

    Offset to start from

  • order ¤ (str | None, default: None ) –

    Field to order results by

  • include_content ¤ (bool, default: False ) –

    Whether to include file content in response

Returns:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤ (str) –

    Name of the operation being performed.

  • service_error_class ¤ (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

update_file async ¤
update_file(
    file_id: str,
    content: bytes | None = None,
    file_type: Literal[
        "UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
    ]
    | None = None,
    content_type: str | None = None,
    metadata: dict[str, Any] | None = None,
    new_name: str | None = None,
    status: str | None = None,
) -> FilesystemRecord

Update a file in the filesystem.

Parameters:

  • file_id ¤ (str) –

    The id of the file to be updated

  • content ¤ (bytes | None, default: None ) –

    Optional new content of the file

  • file_type ¤ (Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default: None ) –

    Optional new type of data

  • content_type ¤ (str | None, default: None ) –

    Optional new MIME type

  • metadata ¤ (dict[str, Any] | None, default: None ) –

    Optional new metadata (will merge with existing)

  • new_name ¤ (str | None, default: None ) –

    Optional new name for the file

  • status ¤ (str | None, default: None ) –

    Optional new status for the file

Returns:

Raises:

upload_files async ¤

Upload multiple files to the filesystem.

Parameters:

  • files ¤ (list[UploadFileData]) –

    List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)

Returns:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

identity ¤

This module is responsible for handling the identity service.

Modules:

Classes:

  • DefaultIdentity

    DefaultIdentity is the default identity strategy.

  • IdentityStrategy

    IdentityStrategy is the abstract base class for all identity strategies.

DefaultIdentity ¤


              flowchart TD
              digitalkin.services.identity.DefaultIdentity[DefaultIdentity]
              digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.identity.identity_strategy.IdentityStrategy --> digitalkin.services.identity.DefaultIdentity
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
                



              click digitalkin.services.identity.DefaultIdentity href "" "digitalkin.services.identity.DefaultIdentity"
              click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

DefaultIdentity is the default identity strategy.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_identity

    Get the identity.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_identity async ¤
get_identity() -> str

Get the identity.

Returns:

  • str ( str ) –

    The identity

IdentityStrategy ¤

IdentityStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.identity.IdentityStrategy[IdentityStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.IdentityStrategy
                


              click digitalkin.services.identity.IdentityStrategy href "" "digitalkin.services.identity.IdentityStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

IdentityStrategy is the abstract base class for all identity strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_identity

    Get the identity.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_identity abstractmethod async ¤
get_identity() -> str

Get the identity.

default_identity ¤

Default identity.

Classes:

DefaultIdentity ¤

              flowchart TD
              digitalkin.services.identity.default_identity.DefaultIdentity[DefaultIdentity]
              digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.identity.identity_strategy.IdentityStrategy --> digitalkin.services.identity.default_identity.DefaultIdentity
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
                



              click digitalkin.services.identity.default_identity.DefaultIdentity href "" "digitalkin.services.identity.default_identity.DefaultIdentity"
              click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

DefaultIdentity is the default identity strategy.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_identity

    Get the identity.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_identity async ¤
get_identity() -> str

Get the identity.

Returns:

  • str ( str ) –

    The identity

identity_strategy ¤

This module contains the abstract base class for identity strategies.

Classes:

  • IdentityStrategy

    IdentityStrategy is the abstract base class for all identity strategies.

IdentityStrategy ¤
IdentityStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
                


              click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

IdentityStrategy is the abstract base class for all identity strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_identity

    Get the identity.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_identity abstractmethod async ¤
get_identity() -> str

Get the identity.

registry ¤

This module is responsible for handling the registry service.

Modules:

Classes:

DefaultRegistry ¤

DefaultRegistry(*args: Any, **kwargs: Any)

              flowchart TD
              digitalkin.services.registry.DefaultRegistry[DefaultRegistry]
              digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.DefaultRegistry
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
                



              click digitalkin.services.registry.DefaultRegistry href "" "digitalkin.services.registry.DefaultRegistry"
              click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default registry strategy using in-memory storage.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • get_setup

    Get setup info (not supported in default registry).

  • get_status

    Get module status.

  • heartbeat

    Send heartbeat to keep module active.

  • register

    Register a module with the registry.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

deregister async ¤
deregister(module_id: str) -> bool

Deregister a module from the registry.

Parameters:

  • module_id ¤
    (str) –

    The module identifier to deregister.

Returns:

  • bool

    True if module was removed, False if not found.

discover_by_id async ¤
discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

get_setup async ¤
get_setup(setup_id: str) -> None

Get setup info (not supported in default registry).

Parameters:

  • setup_id ¤
    (str) –

    The setup identifier.

get_status async ¤
get_status(module_id: str) -> ModuleStatusInfo

Get module status.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

heartbeat async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

register async ¤
register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: Updates existing module or creates new one in local storage.

Parameters:

  • module_id ¤
    (str) –

    Unique module identifier.

  • address ¤
    (str) –

    Network address.

  • port ¤
    (int) –

    Network port.

  • version ¤
    (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None otherwise.

search async ¤
search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤
    (str | None, default: None ) –

    Filter by name (partial match).

  • module_type ¤
    (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤
    (str | None, default: None ) –

    Filter by organization (not used in local storage).

Returns:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

GrpcRegistry ¤

GrpcRegistry(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    client_config: ClientConfig,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.registry.GrpcRegistry[GrpcRegistry]
              digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.GrpcRegistry
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.registry.GrpcRegistry
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.registry.GrpcRegistry
                


              click digitalkin.services.registry.GrpcRegistry href "" "digitalkin.services.registry.GrpcRegistry"
              click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC-based registry client.

This client communicates with the Service Provider's Registry service to perform module discovery, registration, and status management operations.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get_setup

    Get setup info.

  • get_status

    Get module status by fetching the module.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • heartbeat

    Send heartbeat to keep module active.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • register

    Register a module with the registry.

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

deregister async ¤
deregister(module_id: str) -> bool

Deregister a module from the registry.

Note: The registry protocol uses heartbeat expiration for deregistration. When a module stops sending heartbeats, it becomes inactive. This method logs the deregistration intent for observability.

Parameters:

  • module_id ¤
    (str) –

    The module identifier to deregister.

Returns:

  • bool

    True always (heartbeat expiration handles actual deregistration).

discover_by_id async ¤
discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_setup async ¤
get_setup(setup_id: str) -> SetupInfo | None

Get setup info.

Parameters:

  • setup_id ¤
    (str) –

    The setup identifier.

Returns:

  • SetupInfo | None

    SetupInfo if successful, None otherwise.

Raises:

get_status async ¤
get_status(module_id: str) -> ModuleStatusInfo

Get module status by fetching the module.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤
    (str) –

    Name of the operation being performed.

  • service_error_class ¤
    (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

heartbeat async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

register async ¤
register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.

Parameters:

  • module_id ¤
    (str) –

    Unique module identifier.

  • address ¤
    (str) –

    Network address.

  • port ¤
    (int) –

    Network port.

  • version ¤
    (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None if module not found.

Raises:

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

search async ¤
search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤
    (str | None, default: None ) –

    Filter by name (partial match via query).

  • module_type ¤
    (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤
    (str | None, default: None ) –

    Filter by organization.

Returns:

Raises:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

ModuleInfo ¤


              flowchart TD
              digitalkin.services.registry.ModuleInfo[ModuleInfo]

              

              click digitalkin.services.registry.ModuleInfo href "" "digitalkin.services.registry.ModuleInfo"
            

Module information from registry.

ModuleStatusInfo ¤


              flowchart TD
              digitalkin.services.registry.ModuleStatusInfo[ModuleStatusInfo]

              

              click digitalkin.services.registry.ModuleStatusInfo href "" "digitalkin.services.registry.ModuleStatusInfo"
            

Module status response.

RegistryModuleNotFoundError ¤

RegistryModuleNotFoundError(module_id: str)

              flowchart TD
              digitalkin.services.registry.RegistryModuleNotFoundError[RegistryModuleNotFoundError]
              digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]

                              digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.RegistryModuleNotFoundError
                


              click digitalkin.services.registry.RegistryModuleNotFoundError href "" "digitalkin.services.registry.RegistryModuleNotFoundError"
              click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
            

Raised when a module is not found in the registry.

Parameters:

  • module_id ¤
    (str) –

    The ID of the module that was not found.

RegistryModuleStatus ¤


              flowchart TD
              digitalkin.services.registry.RegistryModuleStatus[RegistryModuleStatus]

              

              click digitalkin.services.registry.RegistryModuleStatus href "" "digitalkin.services.registry.RegistryModuleStatus"
            

Module status in the registry.

RegistryModuleType ¤


              flowchart TD
              digitalkin.services.registry.RegistryModuleType[RegistryModuleType]

              

              click digitalkin.services.registry.RegistryModuleType href "" "digitalkin.services.registry.RegistryModuleType"
            

Module type in the registry.

RegistryServiceError ¤


              flowchart TD
              digitalkin.services.registry.RegistryServiceError[RegistryServiceError]

              

              click digitalkin.services.registry.RegistryServiceError href "" "digitalkin.services.registry.RegistryServiceError"
            

Base exception for registry service errors.

RegistryStrategy ¤

RegistryStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.registry.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.RegistryStrategy
                


              click digitalkin.services.registry.RegistryStrategy href "" "digitalkin.services.registry.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for registry strategies.

Defines the interface for registry operations including module discovery, registration, and status management.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • get_setup

    Get setup info.

  • get_status

    Get module status.

  • heartbeat

    Send heartbeat to keep module active.

  • register

    Register a module with the registry.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

deregister abstractmethod async ¤
deregister(module_id: str) -> bool

Deregister a module from the registry.

Parameters:

  • module_id ¤
    (str) –

    The module identifier to deregister.

Returns:

  • bool

    True if deregistration was successful, False otherwise.

discover_by_id abstractmethod async ¤
discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

get_setup abstractmethod async ¤
get_setup(setup_id: str) -> SetupInfo | None

Get setup info.

get_status abstractmethod async ¤
get_status(module_id: str) -> ModuleStatusInfo

Get module status.

heartbeat abstractmethod async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤
    (str) –

    The module identifier.

Returns:

Raises:

register abstractmethod async ¤
register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.

Parameters:

  • module_id ¤
    (str) –

    Unique module identifier.

  • address ¤
    (str) –

    Network address.

  • port ¤
    (int) –

    Network port.

  • version ¤
    (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None otherwise.

search abstractmethod async ¤
search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤
    (str | None, default: None ) –

    Filter by name (partial match via query).

  • module_type ¤
    (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤
    (str | None, default: None ) –

    Filter by organization.

Returns:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

default_registry ¤

Default registry implementation.

Classes:

DefaultRegistry ¤
DefaultRegistry(*args: Any, **kwargs: Any)

              flowchart TD
              digitalkin.services.registry.default_registry.DefaultRegistry[DefaultRegistry]
              digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.default_registry.DefaultRegistry
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
                



              click digitalkin.services.registry.default_registry.DefaultRegistry href "" "digitalkin.services.registry.default_registry.DefaultRegistry"
              click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default registry strategy using in-memory storage.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • get_setup

    Get setup info (not supported in default registry).

  • get_status

    Get module status.

  • heartbeat

    Send heartbeat to keep module active.

  • register

    Register a module with the registry.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

deregister async ¤
deregister(module_id: str) -> bool

Deregister a module from the registry.

Parameters:

  • module_id ¤ (str) –

    The module identifier to deregister.

Returns:

  • bool

    True if module was removed, False if not found.

discover_by_id async ¤
discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

get_setup async ¤
get_setup(setup_id: str) -> None

Get setup info (not supported in default registry).

Parameters:

  • setup_id ¤ (str) –

    The setup identifier.

get_status async ¤
get_status(module_id: str) -> ModuleStatusInfo

Get module status.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

heartbeat async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

register async ¤
register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: Updates existing module or creates new one in local storage.

Parameters:

  • module_id ¤ (str) –

    Unique module identifier.

  • address ¤ (str) –

    Network address.

  • port ¤ (int) –

    Network port.

  • version ¤ (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None otherwise.

search async ¤
search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤ (str | None, default: None ) –

    Filter by name (partial match).

  • module_type ¤ (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤ (str | None, default: None ) –

    Filter by organization (not used in local storage).

Returns:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

exceptions ¤

Registry-specific exceptions.

This module contains custom exceptions for registry service operations.

Classes:

InvalidStatusError ¤
InvalidStatusError(status: int)

              flowchart TD
              digitalkin.services.registry.exceptions.InvalidStatusError[InvalidStatusError]
              digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]

                              digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.exceptions.InvalidStatusError
                


              click digitalkin.services.registry.exceptions.InvalidStatusError href "" "digitalkin.services.registry.exceptions.InvalidStatusError"
              click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
            

Raised when an invalid status is provided.

Parameters:

  • status ¤
    (int) –

    The invalid status value.

ModuleAlreadyExistsError ¤
ModuleAlreadyExistsError(module_id: str)

              flowchart TD
              digitalkin.services.registry.exceptions.ModuleAlreadyExistsError[ModuleAlreadyExistsError]
              digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]

                              digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.exceptions.ModuleAlreadyExistsError
                


              click digitalkin.services.registry.exceptions.ModuleAlreadyExistsError href "" "digitalkin.services.registry.exceptions.ModuleAlreadyExistsError"
              click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
            

Raised when attempting to register an already-registered module.

Parameters:

  • module_id ¤
    (str) –

    The ID of the module that already exists.

RegistryModuleNotFoundError ¤
RegistryModuleNotFoundError(module_id: str)

              flowchart TD
              digitalkin.services.registry.exceptions.RegistryModuleNotFoundError[RegistryModuleNotFoundError]
              digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]

                              digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.exceptions.RegistryModuleNotFoundError
                


              click digitalkin.services.registry.exceptions.RegistryModuleNotFoundError href "" "digitalkin.services.registry.exceptions.RegistryModuleNotFoundError"
              click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
            

Raised when a module is not found in the registry.

Parameters:

  • module_id ¤
    (str) –

    The ID of the module that was not found.

RegistryServiceError ¤

              flowchart TD
              digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]

              

              click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
            

Base exception for registry service errors.

grpc_registry ¤

gRPC Registry client implementation.

This module provides a gRPC-based registry client that communicates with the Service Provider's Registry service.

Classes:

GrpcRegistry ¤
GrpcRegistry(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    client_config: ClientConfig,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.registry.grpc_registry.GrpcRegistry[GrpcRegistry]
              digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.grpc_registry.GrpcRegistry
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.registry.grpc_registry.GrpcRegistry
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.registry.grpc_registry.GrpcRegistry
                


              click digitalkin.services.registry.grpc_registry.GrpcRegistry href "" "digitalkin.services.registry.grpc_registry.GrpcRegistry"
              click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC-based registry client.

This client communicates with the Service Provider's Registry service to perform module discovery, registration, and status management operations.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get_setup

    Get setup info.

  • get_status

    Get module status by fetching the module.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • heartbeat

    Send heartbeat to keep module active.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • register

    Register a module with the registry.

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

deregister async ¤
deregister(module_id: str) -> bool

Deregister a module from the registry.

Note: The registry protocol uses heartbeat expiration for deregistration. When a module stops sending heartbeats, it becomes inactive. This method logs the deregistration intent for observability.

Parameters:

  • module_id ¤ (str) –

    The module identifier to deregister.

Returns:

  • bool

    True always (heartbeat expiration handles actual deregistration).

discover_by_id async ¤
discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_setup async ¤
get_setup(setup_id: str) -> SetupInfo | None

Get setup info.

Parameters:

  • setup_id ¤ (str) –

    The setup identifier.

Returns:

  • SetupInfo | None

    SetupInfo if successful, None otherwise.

Raises:

get_status async ¤
get_status(module_id: str) -> ModuleStatusInfo

Get module status by fetching the module.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤ (str) –

    Name of the operation being performed.

  • service_error_class ¤ (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

heartbeat async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

register async ¤
register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.

Parameters:

  • module_id ¤ (str) –

    Unique module identifier.

  • address ¤ (str) –

    Network address.

  • port ¤ (int) –

    Network port.

  • version ¤ (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None if module not found.

Raises:

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

search async ¤
search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤ (str | None, default: None ) –

    Filter by name (partial match via query).

  • module_type ¤ (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤ (str | None, default: None ) –

    Filter by organization.

Returns:

Raises:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

registry_models ¤

Registry data models.

This module contains Pydantic models for registry service data structures.

Classes:

ModuleStatusInfo ¤

              flowchart TD
              digitalkin.services.registry.registry_models.ModuleStatusInfo[ModuleStatusInfo]

              

              click digitalkin.services.registry.registry_models.ModuleStatusInfo href "" "digitalkin.services.registry.registry_models.ModuleStatusInfo"
            

Module status response.

registry_strategy ¤

Abstract base class for registry strategies.

Classes:

RegistryStrategy ¤
RegistryStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, Any] | None = None,
)

              flowchart TD
              digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
                


              click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for registry strategies.

Defines the interface for registry operations including module discovery, registration, and status management.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • deregister

    Deregister a module from the registry.

  • discover_by_id

    Get module info by ID.

  • get_setup

    Get setup info.

  • get_status

    Get module status.

  • heartbeat

    Send heartbeat to keep module active.

  • register

    Register a module with the registry.

  • search

    Search for modules by criteria.

  • wait_for_ready

    Check if the registry backend is reachable.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

deregister abstractmethod async ¤
deregister(module_id: str) -> bool

Deregister a module from the registry.

Parameters:

  • module_id ¤ (str) –

    The module identifier to deregister.

Returns:

  • bool

    True if deregistration was successful, False otherwise.

discover_by_id abstractmethod async ¤
discover_by_id(module_id: str) -> ModuleInfo

Get module info by ID.

get_setup abstractmethod async ¤
get_setup(setup_id: str) -> SetupInfo | None

Get setup info.

get_status abstractmethod async ¤
get_status(module_id: str) -> ModuleStatusInfo

Get module status.

heartbeat abstractmethod async ¤

Send heartbeat to keep module active.

Parameters:

  • module_id ¤ (str) –

    The module identifier.

Returns:

Raises:

register abstractmethod async ¤
register(module_id: str, address: str, port: int, version: str) -> ModuleInfo | None

Register a module with the registry.

Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.

Parameters:

  • module_id ¤ (str) –

    Unique module identifier.

  • address ¤ (str) –

    Network address.

  • port ¤ (int) –

    Network port.

  • version ¤ (str) –

    Module version.

Returns:

  • ModuleInfo | None

    ModuleInfo if successful, None otherwise.

search abstractmethod async ¤
search(
    name: str | None = None,
    module_type: str | None = None,
    organization_id: str | None = None,
) -> list[ModuleInfo]

Search for modules by criteria.

Parameters:

  • name ¤ (str | None, default: None ) –

    Filter by name (partial match via query).

  • module_type ¤ (str | None, default: None ) –

    Filter by type (archetype, tool).

  • organization_id ¤ (str | None, default: None ) –

    Filter by organization.

Returns:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the registry backend is reachable.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if ready. Default implementation always returns True.

services_config ¤

Service Provider definitions.

Classes:

  • ServicesConfig

    Service class describing the available services in a Module.

ServicesConfig ¤

ServicesConfig(
    services_config_strategies: dict[str, ServicesStrategy | None] = {},
    services_config_params: dict[str, dict[str, Any | None] | None] = {},
    mode: ServicesMode = LOCAL,
    **kwargs: dict[str, Any],
)

              flowchart TD
              digitalkin.services.services_config.ServicesConfig[ServicesConfig]

              

              click digitalkin.services.services_config.ServicesConfig href "" "digitalkin.services.services_config.ServicesConfig"
            

Service class describing the available services in a Module.

This class manages the strategy implementations for various services, allowing them to be switched between local and remote modes.

Parameters:

  • services_config_strategies ¤
    (dict[str, ServicesStrategy | None], default: {} ) –

    Dictionary mapping service names to strategy implementations

  • services_config_params ¤
    (dict[str, dict[str, Any | None] | None], default: {} ) –

    Dictionary mapping service names to configuration parameters

  • mode ¤
    (ServicesMode, default: LOCAL ) –

    The mode of the services (local or remote)

  • **kwargs ¤
    (dict[str, Any], default: {} ) –

    Additional keyword arguments passed to the parent class constructor

Methods:

Attributes:

agent property ¤

Get the agent service strategy class based on the current mode.

communication property ¤
communication: type[CommunicationStrategy]

Get the communication service strategy class based on the current mode.

cost property ¤

Get the cost service strategy class based on the current mode.

filesystem property ¤
filesystem: type[FilesystemStrategy]

Get the filesystem service strategy class based on the current mode.

identity property ¤

Get the identity service strategy class based on the current mode.

registry property ¤

Get the registry service strategy class based on the current mode.

snapshot property ¤

Get the snapshot service strategy class based on the current mode.

storage property ¤

Get the storage service strategy class based on the current mode.

task_manager property ¤
task_manager: type[TaskManagerStrategy]

Get the task_manager service strategy class based on the current mode.

user_profile property ¤
user_profile: type[UserProfileStrategy]

Get the user_profile service strategy class based on the current mode.

get_strategy_config ¤
get_strategy_config(name: str) -> dict[str, Any]

Get the configuration for a specific strategy.

Parameters:

  • name ¤
    (str) –

    The name of the strategy to retrieve the configuration for

Returns:

  • dict[str, Any]

    The configuration for the specified strategy, or empty dict if not found

init_strategy ¤

Initialize a specific strategy.

Parameters:

  • name ¤
    (str) –

    The name of the strategy to initialize

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The setup ID for the strategy

  • setup_version_id ¤
    (str) –

    The setup version ID for the strategy

Returns:

  • Any

    The initialized strategy instance

Raises:

update_mode ¤
update_mode(mode: ServicesMode) -> None

Update the strategy mode.

Parameters:

valid_strategy_names classmethod ¤
valid_strategy_names() -> set[str]

Get the list of valid strategy names.

Returns:

  • set[str]

    The set of valid strategy names.

services_models ¤

This module contains the strategy models for the services.

Classes:

  • ServicesMode

    Mode for strategy execution.

  • ServicesStrategy

    Service class describing the available services in a Module with local and remote attributes.

ServicesMode ¤


              flowchart TD
              digitalkin.services.services_models.ServicesMode[ServicesMode]

              

              click digitalkin.services.services_models.ServicesMode href "" "digitalkin.services.services_models.ServicesMode"
            

Mode for strategy execution.

ServicesStrategy ¤


              flowchart TD
              digitalkin.services.services_models.ServicesStrategy[ServicesStrategy]

              

              click digitalkin.services.services_models.ServicesStrategy href "" "digitalkin.services.services_models.ServicesStrategy"
            

Service class describing the available services in a Module with local and remote attributes.

Attributes:

  • local (type[T]) –

    type

  • remote (type[T]) –

    type

Methods:

  • __getitem__

    Get the service strategy based on the mode.

__getitem__ ¤
__getitem__(mode: str) -> type[T]

Get the service strategy based on the mode.

Parameters:

  • mode ¤
    (str) –

    The mode to get the strategy for.

Returns:

  • type[T]

    The strategy based on the mode.

setup ¤

This module is responsible for handling the setup service.

Modules:

  • default_setup

    This module contains the abstract base class for setup strategies.

  • grpc_setup

    Digital Kin Setup Service gRPC Client.

  • setup_strategy

    This module contains the abstract base class for setup strategies.

default_setup ¤

This module contains the abstract base class for setup strategies.

Classes:

  • DefaultSetup

    Abstract base class for setup strategies.

DefaultSetup ¤
DefaultSetup()

              flowchart TD
              digitalkin.services.setup.default_setup.DefaultSetup[DefaultSetup]
              digitalkin.services.setup.setup_strategy.SetupStrategy[SetupStrategy]

                              digitalkin.services.setup.setup_strategy.SetupStrategy --> digitalkin.services.setup.default_setup.DefaultSetup
                


              click digitalkin.services.setup.default_setup.DefaultSetup href "" "digitalkin.services.setup.default_setup.DefaultSetup"
              click digitalkin.services.setup.setup_strategy.SetupStrategy href "" "digitalkin.services.setup.setup_strategy.SetupStrategy"
            

Abstract base class for setup strategies.

Methods:

__post_init__ ¤
__post_init__(*args: Any, **kwargs: Any) -> None

Lifecycle hook for post-initialization. Subclasses override with specific params.

create_setup async ¤
create_setup(setup_dict: dict[str, Any]) -> str

Create a new setup with comprehensive validation.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary containing setup details.

Returns:

  • bool ( str ) –

    Success status of setup creation.

Raises:

  • ValidationError

    If setup data is invalid.

  • GrpcOperationError

    If gRPC operation fails.

create_setup_version async ¤
create_setup_version(setup_version_dict: dict[str, Any]) -> str

Create a new setup version.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with setup version details.

Returns:

  • str ( str ) –

    version of setup version creation.

Raises:

delete_setup async ¤
delete_setup(setup_dict: dict[str, Any]) -> bool

Delete a setup by its unique identifier.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with the setup 'name'.

Returns:

  • bool ( bool ) –

    Success status of deletion.

delete_setup_version async ¤
delete_setup_version(setup_version_dict: dict[str, Any]) -> bool

Delete a setup version by its unique identifier.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with the setup version 'name'.

Returns:

  • bool ( bool ) –

    Success status of version deletion.

get_setup async ¤
get_setup(setup_dict: dict[str, Any]) -> SetupData

Retrieve a setup by its unique identifier.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with 'name' and optional 'version'.

Returns:

  • SetupData

    Dict[str, Any]: Setup details including optional setup version.

Raises:

get_setup_version async ¤
get_setup_version(setup_version_dict: dict[str, Any]) -> SetupVersionData

Retrieve a setup version by its unique identifier.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with the setup version 'name'.

Returns:

Raises:

list_setups async ¤
list_setups(list_dict: dict[str, Any]) -> dict[str, Any]

List setups with optional filtering and pagination.

Parameters:

  • list_dict ¤ (dict[str, Any]) –

    Dictionary with optional filters.

Returns:

  • dict[str, Any]

    dict[str, Any]: Dictionary with 'setups' list and 'total_count'.

search_setup_versions async ¤
search_setup_versions(setup_version_dict: dict[str, Any]) -> list[SetupVersionData]

Search for setup versions based on filters.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with optional 'name' or 'query_versions' filters.

Returns:

Raises:

update_setup async ¤
update_setup(setup_dict: dict[str, Any]) -> bool

Update an existing setup.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with setup update details.

Returns:

  • bool ( bool ) –

    Success status of the update operation.

Raises:

  • ValidationError

    setup object failed validation.

update_setup_version async ¤
update_setup_version(setup_version_dict: dict[str, Any]) -> bool

Update an existing setup version.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with setup version update details.

Returns:

  • bool ( bool ) –

    Success status of the update operation.

grpc_setup ¤

Digital Kin Setup Service gRPC Client.

Classes:

  • GrpcSetup

    gRPC client implementation for the Setup service.

GrpcSetup ¤
GrpcSetup()

              flowchart TD
              digitalkin.services.setup.grpc_setup.GrpcSetup[GrpcSetup]
              digitalkin.services.setup.setup_strategy.SetupStrategy[SetupStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]

                              digitalkin.services.setup.setup_strategy.SetupStrategy --> digitalkin.services.setup.grpc_setup.GrpcSetup
                
                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.setup.grpc_setup.GrpcSetup
                


              click digitalkin.services.setup.grpc_setup.GrpcSetup href "" "digitalkin.services.setup.grpc_setup.GrpcSetup"
              click digitalkin.services.setup.setup_strategy.SetupStrategy href "" "digitalkin.services.setup.setup_strategy.SetupStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
            

gRPC client implementation for the Setup service.

Communicates with the remote SetupService gRPC server to manage setup configurations and versions.

Methods:

__post_init__ ¤
__post_init__(config: ClientConfig) -> None

Init the channel from a config file.

Need to be call if the user register a gRPC channel.

close async ¤
close() -> None

Release this instance's gRPC channel ref. Subclasses override to release extra resources.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

create_setup async ¤
create_setup(setup_dict: dict[str, Any]) -> str

Create a new setup with comprehensive validation.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary containing setup details.

Returns:

  • bool ( str ) –

    Success status of setup creation.

Raises:

  • ValidationError

    If setup data is invalid.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

create_setup_version async ¤
create_setup_version(setup_version_dict: dict[str, Any]) -> str

Create a new setup version.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with setup version details.

Returns:

  • str ( str ) –

    version of setup version creation.

Raises:

  • ValidationError

    If setup version data is invalid.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

delete_setup async ¤
delete_setup(setup_dict: dict[str, Any]) -> bool

Delete a setup by its unique identifier.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with the setup 'setup_id'.

Returns:

  • bool ( bool ) –

    Success status of deletion.

Raises:

  • ValidationError

    If the setup setup_id is missing.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

delete_setup_version async ¤
delete_setup_version(setup_version_dict: dict[str, Any]) -> bool

Delete a setup version by its unique identifier.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with the setup version 'name'.

Returns:

  • bool ( bool ) –

    Success status of version deletion.

Raises:

  • ValidationError

    If the setup version name is missing.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_setup async ¤
get_setup(setup_dict: dict[str, Any]) -> SetupData

Retrieve a setup by its unique identifier.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with 'name' and optional 'version'.

Returns:

  • SetupData

    dict[str, Any]: Setup details including optional setup version.

Raises:

  • ValidationError

    If the setup name is missing.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

get_setup_version async ¤
get_setup_version(setup_version_dict: dict[str, Any]) -> SetupVersionData

Retrieve a setup version by its unique identifier.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with the setup version 'setup_version_id'.

Returns:

Raises:

  • ValidationError

    If the setup version id is missing.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

handle_grpc_errors async ¤
handle_grpc_errors(operation: str) -> AsyncGenerator[Any, Any]

Context manager for consistent gRPC error handling with detailed logging.

Parameters:

  • operation ¤ (str) –

    Description of the operation being performed (e.g., "Get Setup", "Create Setup Version").

Yields:

Raises:

  • ValueError

    Pydantic model validation failed - input data is malformed.

  • ServerError

    gRPC communication failed - remote service returned error or is unreachable.

  • SetupServiceError

    Unexpected error during setup operation - includes connection/timeout issues.

list_setups async ¤
list_setups(list_dict: dict[str, Any]) -> dict[str, Any]

List setups with optional filtering and pagination.

Parameters:

  • list_dict ¤ (dict[str, Any]) –

    Dictionary with optional filters: - organisation_id: Filter by organisation - owner_id: Filter by owner - limit: Maximum number of results - offset: Number of results to skip

Returns:

  • dict[str, Any]

    dict[str, Any]: Dictionary with 'setups' list and 'total_count'.

Raises:

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

search_setup_versions async ¤
search_setup_versions(setup_version_dict: dict[str, Any]) -> list[SetupVersionData]

Search for setup versions based on filters.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with optional 'name' and 'version' filters.

Returns:

Raises:

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

  • ValidationError

    If both name and version are not provided.

update_setup async ¤
update_setup(setup_dict: dict[str, Any]) -> bool

Update an existing setup.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with setup update details.

Returns:

  • bool ( bool ) –

    Success status of the update operation.

Raises:

  • ValidationError

    If setup data is invalid.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

update_setup_version async ¤
update_setup_version(setup_version_dict: dict[str, Any]) -> bool

Update an existing setup version.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with setup version update details.

Returns:

  • bool ( bool ) –

    Success status of the update operation.

Raises:

  • ValidationError

    If setup version data is invalid.

  • ServerError

    If gRPC operation fails.

  • SetupServiceError

    For any unexpected internal error.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

setup_strategy ¤

This module contains the abstract base class for setup strategies.

Classes:

SetupData ¤

              flowchart TD
              digitalkin.services.setup.setup_strategy.SetupData[SetupData]

              

              click digitalkin.services.setup.setup_strategy.SetupData href "" "digitalkin.services.setup.setup_strategy.SetupData"
            

Pydantic model for Setup data validation.

SetupServiceError ¤

              flowchart TD
              digitalkin.services.setup.setup_strategy.SetupServiceError[SetupServiceError]

              

              click digitalkin.services.setup.setup_strategy.SetupServiceError href "" "digitalkin.services.setup.setup_strategy.SetupServiceError"
            

Base exception for Setup service errors.

SetupStrategy ¤
SetupStrategy()

              flowchart TD
              digitalkin.services.setup.setup_strategy.SetupStrategy[SetupStrategy]

              

              click digitalkin.services.setup.setup_strategy.SetupStrategy href "" "digitalkin.services.setup.setup_strategy.SetupStrategy"
            

Abstract base class for setup strategies.

Methods:

__post_init__ ¤
__post_init__(*args: Any, **kwargs: Any) -> None

Lifecycle hook for post-initialization. Subclasses override with specific params.

create_setup abstractmethod async ¤
create_setup(setup_dict: dict[str, Any]) -> str

Create a new setup with comprehensive validation.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary containing setup details.

Returns:

  • bool ( str ) –

    Success status of setup creation.

Raises:

  • ValidationError

    If setup data is invalid.

  • GrpcOperationError

    If gRPC operation fails.

create_setup_version abstractmethod async ¤
create_setup_version(setup_version_dict: dict[str, Any]) -> str

Create a new setup version.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with setup version details.

Returns:

  • str ( str ) –

    name of setup version creation.

delete_setup abstractmethod async ¤
delete_setup(setup_dict: dict[str, Any]) -> bool

Delete a setup by its unique identifier.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with the setup 'name'.

Returns:

  • bool ( bool ) –

    Success status of deletion.

delete_setup_version abstractmethod async ¤
delete_setup_version(setup_version_dict: dict[str, Any]) -> bool

Delete a setup version by its unique identifier.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with the setup version 'name'.

Returns:

  • bool ( bool ) –

    Success status of version deletion.

get_setup abstractmethod async ¤
get_setup(setup_dict: dict[str, Any]) -> SetupData

Retrieve a setup by its unique identifier.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with 'name' and optional 'version'.

Returns:

  • SetupData

    Dict[str, Any]: Setup details including optional setup version.

get_setup_version abstractmethod async ¤
get_setup_version(setup_version_dict: dict[str, Any]) -> SetupVersionData

Retrieve a setup version by its unique identifier.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with the setup version 'name'.

Returns:

list_setups abstractmethod async ¤
list_setups(list_dict: dict[str, Any]) -> dict[str, Any]

List setups with optional filtering and pagination.

Parameters:

  • list_dict ¤ (dict[str, Any]) –

    Dictionary with optional filters: - organisation_id: Filter by organisation - owner_id: Filter by owner - limit: Maximum number of results - offset: Number of results to skip

Returns:

  • dict[str, Any]

    dict[str, Any]: Dictionary with 'setups' list and 'total_count'.

search_setup_versions abstractmethod async ¤
search_setup_versions(setup_version_dict: dict[str, Any]) -> list[SetupVersionData]

Search for setup versions based on filters.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with optional 'name' and 'version' filters.

Returns:

update_setup abstractmethod async ¤
update_setup(setup_dict: dict[str, Any]) -> bool

Update an existing setup.

Parameters:

  • setup_dict ¤ (dict[str, Any]) –

    Dictionary with setup update details.

Returns:

  • bool ( bool ) –

    Success status of the update operation.

update_setup_version abstractmethod async ¤
update_setup_version(setup_version_dict: dict[str, Any]) -> bool

Update an existing setup version.

Parameters:

  • setup_version_dict ¤ (dict[str, Any]) –

    Dictionary with setup version update details.

Returns:

  • bool ( bool ) –

    Success status of the update operation.

SetupVersionData ¤

              flowchart TD
              digitalkin.services.setup.setup_strategy.SetupVersionData[SetupVersionData]

              

              click digitalkin.services.setup.setup_strategy.SetupVersionData href "" "digitalkin.services.setup.setup_strategy.SetupVersionData"
            

Pydantic model for SetupVersion data validation.

snapshot ¤

This module is responsible for handling the snapshot service.

Modules:

Classes:

DefaultSnapshot ¤


              flowchart TD
              digitalkin.services.snapshot.DefaultSnapshot[DefaultSnapshot]
              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy --> digitalkin.services.snapshot.DefaultSnapshot
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
                



              click digitalkin.services.snapshot.DefaultSnapshot href "" "digitalkin.services.snapshot.DefaultSnapshot"
              click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default snapshot strategy.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • create

    Create a new snapshot in the file system.

  • delete

    Delete snapshots from the file system.

  • get

    Get snapshots from the file system.

  • get_all

    Get all snapshots from the file system.

  • update

    Update snapshots in the file system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

create ¤
create(data: dict[str, Any]) -> str

Create a new snapshot in the file system.

Returns:

  • str ( str ) –

    The ID of the new snapshot

delete ¤
delete(data: dict[str, Any]) -> int

Delete snapshots from the file system.

Returns:

  • int ( int ) –

    The number of snapshots deleted

get ¤
get(data: dict[str, Any]) -> None

Get snapshots from the file system.

get_all ¤
get_all() -> None

Get all snapshots from the file system.

update ¤
update(data: dict[str, Any]) -> int

Update snapshots in the file system.

Returns:

  • int ( int ) –

    The number of snapshots updated

SnapshotStrategy ¤

SnapshotStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.snapshot.SnapshotStrategy[SnapshotStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.SnapshotStrategy
                


              click digitalkin.services.snapshot.SnapshotStrategy href "" "digitalkin.services.snapshot.SnapshotStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for snapshot strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • create

    Create a new snapshot in the file system.

  • delete

    Delete snapshots from the file system.

  • get

    Get snapshots from the file system.

  • get_all

    Get all snapshots from the file system.

  • update

    Update snapshots in the file system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

create abstractmethod ¤
create(data: dict[str, Any]) -> str

Create a new snapshot in the file system.

delete abstractmethod ¤
delete(data: dict[str, Any]) -> int

Delete snapshots from the file system.

get abstractmethod ¤
get(data: dict[str, Any]) -> None

Get snapshots from the file system.

get_all abstractmethod ¤
get_all() -> None

Get all snapshots from the file system.

update abstractmethod ¤
update(data: dict[str, Any]) -> int

Update snapshots in the file system.

default_snapshot ¤

Default snapshot.

Classes:

DefaultSnapshot ¤

              flowchart TD
              digitalkin.services.snapshot.default_snapshot.DefaultSnapshot[DefaultSnapshot]
              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy --> digitalkin.services.snapshot.default_snapshot.DefaultSnapshot
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
                



              click digitalkin.services.snapshot.default_snapshot.DefaultSnapshot href "" "digitalkin.services.snapshot.default_snapshot.DefaultSnapshot"
              click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default snapshot strategy.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • create

    Create a new snapshot in the file system.

  • delete

    Delete snapshots from the file system.

  • get

    Get snapshots from the file system.

  • get_all

    Get all snapshots from the file system.

  • update

    Update snapshots in the file system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

create ¤
create(data: dict[str, Any]) -> str

Create a new snapshot in the file system.

Returns:

  • str ( str ) –

    The ID of the new snapshot

delete ¤
delete(data: dict[str, Any]) -> int

Delete snapshots from the file system.

Returns:

  • int ( int ) –

    The number of snapshots deleted

get ¤
get(data: dict[str, Any]) -> None

Get snapshots from the file system.

get_all ¤
get_all() -> None

Get all snapshots from the file system.

update ¤
update(data: dict[str, Any]) -> int

Update snapshots in the file system.

Returns:

  • int ( int ) –

    The number of snapshots updated

snapshot_strategy ¤

This module contains the abstract base class for snapshot strategies.

Classes:

SnapshotStrategy ¤
SnapshotStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
                


              click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for snapshot strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • create

    Create a new snapshot in the file system.

  • delete

    Delete snapshots from the file system.

  • get

    Get snapshots from the file system.

  • get_all

    Get all snapshots from the file system.

  • update

    Update snapshots in the file system.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

create abstractmethod ¤
create(data: dict[str, Any]) -> str

Create a new snapshot in the file system.

delete abstractmethod ¤
delete(data: dict[str, Any]) -> int

Delete snapshots from the file system.

get abstractmethod ¤
get(data: dict[str, Any]) -> None

Get snapshots from the file system.

get_all abstractmethod ¤
get_all() -> None

Get all snapshots from the file system.

update abstractmethod ¤
update(data: dict[str, Any]) -> int

Update snapshots in the file system.

storage ¤

This module is responsible for handling the storage service.

Modules:

  • default_storage

    This module implements the default storage strategy.

  • grpc_storage

    This module implements the default storage strategy.

  • storage_strategy

    This module contains the abstract base class for storage strategies.

Classes:

  • DefaultStorage

    Persist records in a local JSON file for quick local development.

  • GrpcStorage

    gRPC client implementation for the Storage service.

  • StorageStrategy

    Define CRUD + list/remove-collection against a collection/record store.

DefaultStorage ¤

DefaultStorage(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
    storage_file_path: str = "local_storage",
)

              flowchart TD
              digitalkin.services.storage.DefaultStorage[DefaultStorage]
              digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.DefaultStorage
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
                



              click digitalkin.services.storage.DefaultStorage href "" "digitalkin.services.storage.DefaultStorage"
              click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Persist records in a local JSON file for quick local development.

a JSON object of

{ ":": { ... StorageRecord fields ... },

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • list

    Get all records in a collection under the given scope.

  • read

    Get a record by key under the given scope.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

list async ¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

read async ¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name to retrieve data for

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

remove async ¤
remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤
store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str | None) –

    The unique ID for the record (optional)

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤
update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • data ¤
    (dict[str, Any]) –

    The new data to store

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤
upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID for the record

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

GrpcStorage ¤

GrpcStorage(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
    client_config: ClientConfig,
)

              flowchart TD
              digitalkin.services.storage.GrpcStorage[GrpcStorage]
              digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]

                              digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.GrpcStorage
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.storage.GrpcStorage
                


              click digitalkin.services.storage.GrpcStorage href "" "digitalkin.services.storage.GrpcStorage"
              click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
            

gRPC client implementation for the Storage service.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • list

    Get all records in a collection under the given scope.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • read

    Get a record by key under the given scope.

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

list async ¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

read async ¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name to retrieve data for

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

remove async ¤
remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤
store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str | None) –

    The unique ID for the record (optional)

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤
update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • data ¤
    (dict[str, Any]) –

    The new data to store

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤
upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID for the record

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

StorageStrategy ¤

StorageStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
)

              flowchart TD
              digitalkin.services.storage.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.StorageStrategy
                


              click digitalkin.services.storage.StorageStrategy href "" "digitalkin.services.storage.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Define CRUD + list/remove-collection against a collection/record store.

Records are scoped by a context string (the proto field), which is either self.mission_id (mission scope, the default) or self.setup_version_id (setup-version scope). Both attributes are expected to already contain the full prefix (missions:<id> / setup_versions:<id>).

Public methods accept scope: Literal["mission", "setup"] (default "mission"); internally we resolve it to the matching context string and pass that to the abstract _store/_read/_update/_remove/_list/_remove_collection.

Parameters:

  • mission_id ¤
    (str) –

    Already-prefixed mission context (missions:<id>).

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    Already-prefixed setup-version context (setup_versions:<id>).

  • config ¤
    (dict[str, type[BaseModel]]) –

    A dictionary mapping names to Pydantic model classes

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • list

    Get all records in a collection under the given scope.

  • read

    Get a record by key under the given scope.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

list async ¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

read async ¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name to retrieve data for

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

remove async ¤
remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤
store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str | None) –

    The unique ID for the record (optional)

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤
update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID of the record

  • data ¤
    (dict[str, Any]) –

    The new data to store

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤
upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤
    (str) –

    The unique name for the record type

  • record_id ¤
    (str) –

    The unique ID for the record

  • data ¤
    (dict[str, Any]) –

    The data to store

  • data_type ¤
    (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤
    (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

default_storage ¤

This module implements the default storage strategy.

Classes:

  • DefaultStorage

    Persist records in a local JSON file for quick local development.

DefaultStorage ¤
DefaultStorage(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
    storage_file_path: str = "local_storage",
)

              flowchart TD
              digitalkin.services.storage.default_storage.DefaultStorage[DefaultStorage]
              digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.default_storage.DefaultStorage
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
                



              click digitalkin.services.storage.default_storage.DefaultStorage href "" "digitalkin.services.storage.default_storage.DefaultStorage"
              click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Persist records in a local JSON file for quick local development.

a JSON object of

{ ":": { ... StorageRecord fields ... },

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • list

    Get all records in a collection under the given scope.

  • read

    Get a record by key under the given scope.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

list async ¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

read async ¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name to retrieve data for

  • record_id ¤ (str) –

    The unique ID of the record

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

remove async ¤
remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID of the record

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤
store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str | None) –

    The unique ID for the record (optional)

  • data ¤ (dict[str, Any]) –

    The data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤ (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤
update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID of the record

  • data ¤ (dict[str, Any]) –

    The new data to store

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤
upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID for the record

  • data ¤ (dict[str, Any]) –

    The data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

grpc_storage ¤

This module implements the default storage strategy.

Classes:

  • GrpcStorage

    gRPC client implementation for the Storage service.

GrpcStorage ¤
GrpcStorage(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
    client_config: ClientConfig,
)

              flowchart TD
              digitalkin.services.storage.grpc_storage.GrpcStorage[GrpcStorage]
              digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]

                              digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.grpc_storage.GrpcStorage
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.storage.grpc_storage.GrpcStorage
                


              click digitalkin.services.storage.grpc_storage.GrpcStorage href "" "digitalkin.services.storage.grpc_storage.GrpcStorage"
              click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
            

gRPC client implementation for the Storage service.

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • list

    Get all records in a collection under the given scope.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • read

    Get a record by key under the given scope.

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

list async ¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

read async ¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name to retrieve data for

  • record_id ¤ (str) –

    The unique ID of the record

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

remove async ¤
remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID of the record

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤
store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str | None) –

    The unique ID for the record (optional)

  • data ¤ (dict[str, Any]) –

    The data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤ (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤
update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID of the record

  • data ¤ (dict[str, Any]) –

    The new data to store

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤
upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID for the record

  • data ¤ (dict[str, Any]) –

    The data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

storage_strategy ¤

This module contains the abstract base class for storage strategies.

Classes:

  • DataType

    Enum defining the types of data that can be stored.

  • StorageRecord

    A single record stored in a collection, with metadata.

  • StorageServiceError

    Base exception for Setup service errors.

  • StorageStrategy

    Define CRUD + list/remove-collection against a collection/record store.

DataType ¤

              flowchart TD
              digitalkin.services.storage.storage_strategy.DataType[DataType]

              

              click digitalkin.services.storage.storage_strategy.DataType href "" "digitalkin.services.storage.storage_strategy.DataType"
            

Enum defining the types of data that can be stored.

StorageRecord ¤

              flowchart TD
              digitalkin.services.storage.storage_strategy.StorageRecord[StorageRecord]

              

              click digitalkin.services.storage.storage_strategy.StorageRecord href "" "digitalkin.services.storage.storage_strategy.StorageRecord"
            

A single record stored in a collection, with metadata.

StorageServiceError ¤

              flowchart TD
              digitalkin.services.storage.storage_strategy.StorageServiceError[StorageServiceError]

              

              click digitalkin.services.storage.storage_strategy.StorageServiceError href "" "digitalkin.services.storage.storage_strategy.StorageServiceError"
            

Base exception for Setup service errors.

StorageStrategy ¤
StorageStrategy(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    config: dict[str, type[BaseModel]],
)

              flowchart TD
              digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
                


              click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Define CRUD + list/remove-collection against a collection/record store.

Records are scoped by a context string (the proto field), which is either self.mission_id (mission scope, the default) or self.setup_version_id (setup-version scope). Both attributes are expected to already contain the full prefix (missions:<id> / setup_versions:<id>).

Public methods accept scope: Literal["mission", "setup"] (default "mission"); internally we resolve it to the matching context string and pass that to the abstract _store/_read/_update/_remove/_list/_remove_collection.

Parameters:

  • mission_id ¤
    (str) –

    Already-prefixed mission context (missions:<id>).

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    Already-prefixed setup-version context (setup_versions:<id>).

  • config ¤
    (dict[str, type[BaseModel]]) –

    A dictionary mapping names to Pydantic model classes

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • list

    Get all records in a collection under the given scope.

  • read

    Get a record by key under the given scope.

  • remove

    Delete a record from the storage under the given scope.

  • remove_collection

    Wipe a collection clean under the given scope.

  • store

    Store a new record in the storage.

  • update

    Validate & overwrite an existing record under the given scope.

  • upsert

    Insert or update a record atomically under the given scope.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

list async ¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]

Get all records in a collection under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to list (default: "mission").

Returns:

read async ¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None

Get a record by key under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name to retrieve data for

  • record_id ¤ (str) –

    The unique ID of the record

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to read from (default: "mission").

Returns:

  • StorageRecord | None

    The matching record if it exists, otherwise None.

remove async ¤
remove(collection: str, record_id: str, scope: Scope = 'mission') -> bool

Delete a record from the storage under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID of the record

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

remove_collection async ¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool

Wipe a collection clean under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the records live under (default: "mission").

Returns:

  • bool

    True if the deletion was successful, False otherwise

store async ¤
store(
    collection: str,
    record_id: str | None,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Store a new record in the storage.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str | None) –

    The unique ID for the record (optional)

  • data ¤ (dict[str, Any]) –

    The data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤ (Scope, default: 'mission' ) –

    "mission" (default) writes under the current mission context; "setup" writes under the setup-version context.

Returns:

Raises:

  • ValueError

    If the data type is invalid or if validation fails

update async ¤
update(
    collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None

Validate & overwrite an existing record under the given scope.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID of the record

  • data ¤ (dict[str, Any]) –

    The new data to store

  • scope ¤ (Scope, default: 'mission' ) –

    Which context the record lives under (default: "mission").

Returns:

upsert async ¤
upsert(
    collection: str,
    record_id: str,
    data: dict[str, Any],
    data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
    scope: Scope = "mission",
) -> StorageRecord

Insert or update a record atomically under the given scope.

If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.

Parameters:

  • collection ¤ (str) –

    The unique name for the record type

  • record_id ¤ (str) –

    The unique ID for the record

  • data ¤ (dict[str, Any]) –

    The data to store

  • data_type ¤ (Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default: 'OUTPUT' ) –

    The type of data being stored (default: OUTPUT)

  • scope ¤ (Scope, default: 'mission' ) –

    Which context to upsert under (default: "mission").

Returns:

Raises:

task_manager ¤

Task manager signal service.

Modules:

Classes:

DefaultTaskManager ¤

DefaultTaskManager(
    mission_id: str = "", setup_id: str = "", setup_version_id: str = ""
)

              flowchart TD
              digitalkin.services.task_manager.DefaultTaskManager[DefaultTaskManager]
              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]

                              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy --> digitalkin.services.task_manager.DefaultTaskManager
                


              click digitalkin.services.task_manager.DefaultTaskManager href "" "digitalkin.services.task_manager.DefaultTaskManager"
              click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
            

In-memory task signal service for single-process deployments.

Parameters:

  • mission_id ¤
    (str, default: '' ) –

    Mission identifier (unused, required by init_strategy convention).

  • setup_id ¤
    (str, default: '' ) –

    Setup identifier (unused, required by init_strategy convention).

  • setup_version_id ¤
    (str, default: '' ) –

    Setup version identifier (unused, required by init_strategy convention).

Methods:

  • close

    Poison all subscribers and clear state.

  • send_signal

    Create or update a signal record and broadcast to subscribers.

  • subscribe_signals

    Subscribe to signal updates via an in-memory queue.

  • unsubscribe_signals

    Unsubscribe by sending a poison pill and removing the subscriber.

close async ¤
close() -> None

Poison all subscribers and clear state.

send_signal async ¤
send_signal(task_id: str, data: dict[str, Any]) -> dict[str, Any]

Create or update a signal record and broadcast to subscribers.

Parameters:

  • task_id ¤
    (str) –

    Unique task identifier.

  • data ¤
    (dict[str, Any]) –

    Signal data to upsert.

Returns:

subscribe_signals async ¤
subscribe_signals(
    task_id: str = "",
) -> tuple[str, AsyncGenerator[dict[str, Any], None]]

Subscribe to signal updates via an in-memory queue.

Parameters:

  • task_id ¤
    (str, default: '' ) –

    Task identifier (unused in local mode, broadcasts all signals).

Returns:

unsubscribe_signals async ¤
unsubscribe_signals(sub_id: str) -> None

Unsubscribe by sending a poison pill and removing the subscriber.

Parameters:

  • sub_id ¤
    (str) –

    Subscription identifier.

TaskManagerStrategy ¤


              flowchart TD
              digitalkin.services.task_manager.TaskManagerStrategy[TaskManagerStrategy]

              

              click digitalkin.services.task_manager.TaskManagerStrategy href "" "digitalkin.services.task_manager.TaskManagerStrategy"
            

Abstract strategy for task manager signal management.

Defines the contract for upsert, subscribe, unsubscribe, and close operations used by TaskSession, TaskExecutor, and BaseTaskManager.

Methods:

close abstractmethod async ¤
close() -> None

Close the signal service and release resources.

send_signal abstractmethod async ¤
send_signal(task_id: str, data: dict[str, Any]) -> dict[str, Any]

Create or update a signal record for a task.

Parameters:

  • task_id ¤
    (str) –

    Unique task identifier.

  • data ¤
    (dict[str, Any]) –

    Signal data to upsert.

Returns:

subscribe_signals abstractmethod async ¤
subscribe_signals(task_id: str) -> tuple[str, AsyncGenerator[dict[str, Any], None]]

Subscribe to signal updates for a specific task.

Parameters:

  • task_id ¤
    (str) –

    Unique task identifier to subscribe to.

Returns:

unsubscribe_signals abstractmethod async ¤
unsubscribe_signals(sub_id: str) -> None

Unsubscribe from signal updates.

Parameters:

  • sub_id ¤
    (str) –

    Subscription identifier returned by subscribe_signals.

default_task_manager ¤

In-memory implementation of TaskManagerStrategy.

Classes:

DefaultTaskManager ¤
DefaultTaskManager(
    mission_id: str = "", setup_id: str = "", setup_version_id: str = ""
)

              flowchart TD
              digitalkin.services.task_manager.default_task_manager.DefaultTaskManager[DefaultTaskManager]
              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]

                              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy --> digitalkin.services.task_manager.default_task_manager.DefaultTaskManager
                


              click digitalkin.services.task_manager.default_task_manager.DefaultTaskManager href "" "digitalkin.services.task_manager.default_task_manager.DefaultTaskManager"
              click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
            

In-memory task signal service for single-process deployments.

Parameters:

  • mission_id ¤
    (str, default: '' ) –

    Mission identifier (unused, required by init_strategy convention).

  • setup_id ¤
    (str, default: '' ) –

    Setup identifier (unused, required by init_strategy convention).

  • setup_version_id ¤
    (str, default: '' ) –

    Setup version identifier (unused, required by init_strategy convention).

Methods:

  • close

    Poison all subscribers and clear state.

  • send_signal

    Create or update a signal record and broadcast to subscribers.

  • subscribe_signals

    Subscribe to signal updates via an in-memory queue.

  • unsubscribe_signals

    Unsubscribe by sending a poison pill and removing the subscriber.

close async ¤
close() -> None

Poison all subscribers and clear state.

send_signal async ¤
send_signal(task_id: str, data: dict[str, Any]) -> dict[str, Any]

Create or update a signal record and broadcast to subscribers.

Parameters:

  • task_id ¤ (str) –

    Unique task identifier.

  • data ¤ (dict[str, Any]) –

    Signal data to upsert.

Returns:

subscribe_signals async ¤
subscribe_signals(
    task_id: str = "",
) -> tuple[str, AsyncGenerator[dict[str, Any], None]]

Subscribe to signal updates via an in-memory queue.

Parameters:

  • task_id ¤ (str, default: '' ) –

    Task identifier (unused in local mode, broadcasts all signals).

Returns:

unsubscribe_signals async ¤
unsubscribe_signals(sub_id: str) -> None

Unsubscribe by sending a poison pill and removing the subscriber.

Parameters:

  • sub_id ¤ (str) –

    Subscription identifier.

grpc_task_manager ¤

gRPC implementation of TaskManagerStrategy using TaskManagerService.

Classes:

  • GrpcTaskManager

    gRPC-backed task signal service using TaskManagerService.

GrpcTaskManager ¤
GrpcTaskManager(
    mission_id: str,
    setup_id: str,
    setup_version_id: str,
    client_config: ClientConfig,
    *,
    poll_interval: float = float(get("DIGITALKIN_SIGNAL_POLL_INTERVAL", "1.0")),
    initial_poll_interval: float = float(
        get("DIGITALKIN_SIGNAL_INITIAL_POLL_INTERVAL", "0.1")
    ),
)

              flowchart TD
              digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager[GrpcTaskManager]
              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy --> digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager
                
                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager
                


              click digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager href "" "digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager"
              click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC-backed task signal service using TaskManagerService.

Signal polling is delegated to a shared _SharedPoller per gRPC address, so N concurrent tasks share one controlled polling loop instead of N independent loops hammering the TaskManagerService.

Parameters:

  • mission_id ¤
    (str) –

    Mission identifier (unused, required by init_strategy convention).

  • setup_id ¤
    (str) –

    Setup identifier (unused, required by init_strategy convention).

  • setup_version_id ¤
    (str) –

    Setup version identifier (unused, required by init_strategy convention).

  • client_config ¤
    (ClientConfig) –

    gRPC client configuration.

  • poll_interval ¤
    (float, default: float(get('DIGITALKIN_SIGNAL_POLL_INTERVAL', '1.0')) ) –

    Maximum seconds between GetSignals polls.

  • initial_poll_interval ¤
    (float, default: float(get('DIGITALKIN_SIGNAL_INITIAL_POLL_INTERVAL', '0.1')) ) –

    Starting poll interval before exponential ramp-up.

Raises:

  • ImportError

    If agentic_mesh_protocol.task_manager.v1 is not installed.

Methods:

  • close

    Stop all subscriptions, flush pending signals, and close the gRPC channel.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • send_signal

    Enqueue a signal for batched delivery via gRPC SendSignals.

  • subscribe_signals

    Subscribe to signal updates via the shared poller.

  • unsubscribe_signals

    Stop the subscription and wake its consumer via the shared poller.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Stop all subscriptions, flush pending signals, and close the gRPC channel.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤ (str) –

    Name of the operation being performed.

  • service_error_class ¤ (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

send_signal async ¤
send_signal(task_id: str, data: dict[str, Any]) -> dict[str, Any]

Enqueue a signal for batched delivery via gRPC SendSignals.

Signals are accumulated in a shared per-channel send buffer and flushed in a single SendSignalsRequest either when the batch hits 50 items or after 100 ms — whichever comes first.

Parameters:

  • task_id ¤ (str) –

    Unique task identifier.

  • data ¤ (dict[str, Any]) –

    Signal data to upsert.

Returns:

  • dict[str, Any]

    The upserted record as a dict.

Raises:

subscribe_signals async ¤
subscribe_signals(task_id: str) -> tuple[str, AsyncGenerator[dict[str, Any], None]]

Subscribe to signal updates via the shared poller.

Instead of an independent polling loop, this registers the task_id with the shared _SharedPoller and yields signals from a queue.

Parameters:

  • task_id ¤ (str) –

    Unique task identifier to poll signals for.

Returns:

unsubscribe_signals async ¤
unsubscribe_signals(sub_id: str) -> None

Stop the subscription and wake its consumer via the shared poller.

Parameters:

  • sub_id ¤ (str) –

    Subscription identifier.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

task_manager_strategy ¤

Abstract interface for task manager signal management.

Classes:

TaskManagerServiceError ¤

              flowchart TD
              digitalkin.services.task_manager.task_manager_strategy.TaskManagerServiceError[TaskManagerServiceError]

              

              click digitalkin.services.task_manager.task_manager_strategy.TaskManagerServiceError href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerServiceError"
            

Error raised by task manager service operations.

TaskManagerStrategy ¤

              flowchart TD
              digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]

              

              click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
            

Abstract strategy for task manager signal management.

Defines the contract for upsert, subscribe, unsubscribe, and close operations used by TaskSession, TaskExecutor, and BaseTaskManager.

Methods:

close abstractmethod async ¤
close() -> None

Close the signal service and release resources.

send_signal abstractmethod async ¤
send_signal(task_id: str, data: dict[str, Any]) -> dict[str, Any]

Create or update a signal record for a task.

Parameters:

  • task_id ¤ (str) –

    Unique task identifier.

  • data ¤ (dict[str, Any]) –

    Signal data to upsert.

Returns:

subscribe_signals abstractmethod async ¤
subscribe_signals(task_id: str) -> tuple[str, AsyncGenerator[dict[str, Any], None]]

Subscribe to signal updates for a specific task.

Parameters:

  • task_id ¤ (str) –

    Unique task identifier to subscribe to.

Returns:

unsubscribe_signals abstractmethod async ¤
unsubscribe_signals(sub_id: str) -> None

Unsubscribe from signal updates.

Parameters:

  • sub_id ¤ (str) –

    Subscription identifier returned by subscribe_signals.

user_profile ¤

UserProfile service package.

Modules:

Classes:

DefaultUserProfile ¤

DefaultUserProfile(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.user_profile.DefaultUserProfile[DefaultUserProfile]
              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.DefaultUserProfile
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
                



              click digitalkin.services.user_profile.DefaultUserProfile href "" "digitalkin.services.user_profile.DefaultUserProfile"
              click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default user profile strategy with in-memory storage.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version

Methods:

  • add_user_profile

    Add a user profile to the in-memory database (helper for testing).

  • close

    Release resources held by this strategy. No-op by default.

  • get_user_profile

    Get user profile from in-memory storage.

add_user_profile ¤
add_user_profile(user_profile_data: dict[str, Any]) -> None

Add a user profile to the in-memory database (helper for testing).

Parameters:

  • user_profile_data ¤
    (dict[str, Any]) –

    Dictionary containing user profile data

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_user_profile async ¤
get_user_profile() -> dict[str, Any] | None

Get user profile from in-memory storage.

Returns:

  • dict[str, Any] | None

    User profile data, or None if not found.

GrpcUserProfile ¤


              flowchart TD
              digitalkin.services.user_profile.GrpcUserProfile[GrpcUserProfile]
              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.GrpcUserProfile
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.user_profile.GrpcUserProfile
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.user_profile.GrpcUserProfile
                


              click digitalkin.services.user_profile.GrpcUserProfile href "" "digitalkin.services.user_profile.GrpcUserProfile"
              click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC client implementation for the UserProfile service.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version

  • client_config ¤
    (ClientConfig) –

    Client configuration for gRPC connection

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get_user_profile

    Get user profile by mission_id (which maps to user_id).

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤
    (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤
    (Any) –

    gRPC protobuf request object

  • timeout ¤
    (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_user_profile async ¤
get_user_profile() -> dict[str, Any] | None

Get user profile by mission_id (which maps to user_id).

Returns:

  • dict[str, Any] | None

    User profile data, or None if not found.

Raises:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤
    (str) –

    Name of the operation being performed.

  • service_error_class ¤
    (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤
    (str) –

    RPC method name on self.stub.

  • request ¤
    (Any) –

    gRPC request protobuf.

  • timeout ¤
    (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤
    (str) –

    Channel cache key to release.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤
    (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

UserProfileServiceError ¤


              flowchart TD
              digitalkin.services.user_profile.UserProfileServiceError[UserProfileServiceError]

              

              click digitalkin.services.user_profile.UserProfileServiceError href "" "digitalkin.services.user_profile.UserProfileServiceError"
            

Base exception for UserProfile service errors.

UserProfileStrategy ¤

UserProfileStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.user_profile.UserProfileStrategy[UserProfileStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.UserProfileStrategy
                


              click digitalkin.services.user_profile.UserProfileStrategy href "" "digitalkin.services.user_profile.UserProfileStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for UserProfile strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_user_profile

    Get user profile data.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_user_profile abstractmethod async ¤
get_user_profile() -> dict[str, Any] | None

Get user profile data.

Returns:

  • dict[str, Any] | None

    User profile data, or None if not found.

Raises:

default_user_profile ¤

Default user profile implementation.

Classes:

DefaultUserProfile ¤
DefaultUserProfile(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.user_profile.default_user_profile.DefaultUserProfile[DefaultUserProfile]
              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.default_user_profile.DefaultUserProfile
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
                



              click digitalkin.services.user_profile.default_user_profile.DefaultUserProfile href "" "digitalkin.services.user_profile.default_user_profile.DefaultUserProfile"
              click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Default user profile strategy with in-memory storage.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version

Methods:

  • add_user_profile

    Add a user profile to the in-memory database (helper for testing).

  • close

    Release resources held by this strategy. No-op by default.

  • get_user_profile

    Get user profile from in-memory storage.

add_user_profile ¤
add_user_profile(user_profile_data: dict[str, Any]) -> None

Add a user profile to the in-memory database (helper for testing).

Parameters:

  • user_profile_data ¤ (dict[str, Any]) –

    Dictionary containing user profile data

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_user_profile async ¤
get_user_profile() -> dict[str, Any] | None

Get user profile from in-memory storage.

Returns:

  • dict[str, Any] | None

    User profile data, or None if not found.

grpc_user_profile ¤

Digital Kin UserProfile Service gRPC Client.

Classes:

  • GrpcUserProfile

    gRPC client implementation for the UserProfile service.

GrpcUserProfile ¤

              flowchart TD
              digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile[GrpcUserProfile]
              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
              digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
              digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]

                              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile
                                digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
                

                digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile
                
                digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile
                


              click digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile href "" "digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile"
              click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
              click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
              click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
            

gRPC client implementation for the UserProfile service.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup

  • setup_version_id ¤
    (str) –

    The ID of the setup version

  • client_config ¤
    (ClientConfig) –

    Client configuration for gRPC connection

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • close_all_cached_channels

    Close all cached channels and reset the cache.

  • close_channel

    Release this instance's ref on the cached channel.

  • exec_grpc_query

    Execute a gRPC query with from the query's rpc endpoint name.

  • get_user_profile

    Get user profile by mission_id (which maps to user_id).

  • handle_grpc_errors

    Handle gRPC errors for the given operation.

  • poll_grpc

    Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

  • release_cached_channel

    Decrement refcount for a cache key and close channel when last ref is released.

  • wait_for_ready

    Check if the gRPC channel can connect within timeout.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

close_all_cached_channels async classmethod ¤
close_all_cached_channels() -> None

Close all cached channels and reset the cache.

Intended for server shutdown to ensure clean resource release.

close_channel async ¤
close_channel() -> None

Release this instance's ref on the cached channel.

The underlying channel is only closed when the last ref is released.

exec_grpc_query async ¤
exec_grpc_query(query_endpoint: str, request: Any, timeout: float | None = None) -> Any

Execute a gRPC query with from the query's rpc endpoint name.

Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.

Parameters:

  • query_endpoint ¤ (str) –

    rpc query name (e.g., "GetSetup", "CreateSetupVersion")

  • request ¤ (Any) –

    gRPC protobuf request object

  • timeout ¤ (float | None, default: None ) –

    Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.

Returns:

  • Any

    gRPC protobuf response object.

Raises:

  • ServerError

    gRPC error with status code and details for caller to handle.

get_user_profile async ¤
get_user_profile() -> dict[str, Any] | None

Get user profile by mission_id (which maps to user_id).

Returns:

  • dict[str, Any] | None

    User profile data, or None if not found.

Raises:

handle_grpc_errors async ¤
handle_grpc_errors(
    operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]

Handle gRPC errors for the given operation.

Parameters:

  • operation ¤ (str) –

    Name of the operation being performed.

  • service_error_class ¤ (type[Exception] | None, default: None ) –

    Optional specific service exception class to raise. If not provided, uses the generic ServerError.

Yields:

Raises:

  • ServerError

    For gRPC-related errors.

  • service_error_class

    For service-specific errors if provided.

poll_grpc async ¤
poll_grpc(endpoint: str, request: Any, *, timeout: float) -> Any | None

Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).

Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.

Parameters:

  • endpoint ¤ (str) –

    RPC method name on self.stub.

  • request ¤ (Any) –

    gRPC request protobuf.

  • timeout ¤ (float) –

    Seconds before treating as 'no result available'.

Returns:

  • Any | None

    gRPC response, or None if DEADLINE_EXCEEDED.

Raises:

  • ServerError

    For any non-DEADLINE_EXCEEDED gRPC error.

release_cached_channel async classmethod ¤
release_cached_channel(key: str) -> None

Decrement refcount for a cache key and close channel when last ref is released.

Parameters:

  • key ¤ (str) –

    Channel cache key to release.

wait_for_ready async ¤
wait_for_ready(timeout: float = 1.0) -> bool

Check if the gRPC channel can connect within timeout.

Uses channel_ready() which resolves when the HTTP/2 connection is established and the server is accepting RPCs.

Parameters:

  • timeout ¤ (float, default: 1.0 ) –

    Max seconds to wait for connectivity.

Returns:

  • bool

    True if channel reached READY state, False if timeout or no channel.

user_profile_strategy ¤

This module contains the abstract base class for UserProfile strategies.

Classes:

UserProfileServiceError ¤

              flowchart TD
              digitalkin.services.user_profile.user_profile_strategy.UserProfileServiceError[UserProfileServiceError]

              

              click digitalkin.services.user_profile.user_profile_strategy.UserProfileServiceError href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileServiceError"
            

Base exception for UserProfile service errors.

UserProfileStrategy ¤
UserProfileStrategy(mission_id: str, setup_id: str, setup_version_id: str)

              flowchart TD
              digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
              digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]

                              digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
                


              click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
              click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
            

Abstract base class for UserProfile strategies.

Parameters:

  • mission_id ¤
    (str) –

    The ID of the mission this strategy is associated with

  • setup_id ¤
    (str) –

    The ID of the setup this strategy is associated with

  • setup_version_id ¤
    (str) –

    The ID of the setup version this strategy is associated with

Methods:

  • close

    Release resources held by this strategy. No-op by default.

  • get_user_profile

    Get user profile data.

close async ¤
close() -> None

Release resources held by this strategy. No-op by default.

get_user_profile abstractmethod async ¤
get_user_profile() -> dict[str, Any] | None

Get user profile data.

Returns:

  • dict[str, Any] | None

    User profile data, or None if not found.

Raises:

utils ¤

General utils folder.

Modules:

Classes:

Functions:

  • get_conditional_metadata

    Extract ConditionalField from field metadata.

  • get_dynamic_metadata

    Extract DynamicField metadata from a FieldInfo's metadata list.

  • get_fetchers

    Extract fetchers from a field's DynamicField metadata.

  • has_conditional

    Check if field has ConditionalField metadata.

  • has_dynamic

    Check if a field has DynamicField metadata.

  • resolve

    Resolve all dynamic fetchers to their actual values in parallel.

  • resolve_safe

    Resolve fetchers with structured error handling.

ConditionalField dataclass ¤

ConditionalField(
    trigger: str, show_when: bool | str | list[str], required_when_shown: bool = True
)

Metadata for conditional field visibility.

Use with typing.Annotated to mark fields that should only appear when a trigger field has a specific value.

Parameters:

  • trigger ¤

    (str) –

    Name of the field that controls visibility.

  • show_when ¤

    (bool | str | list[str]) –

    Value(s) that trigger field must have to show this field. Can be a boolean, string, or list of strings for multiple values.

  • required_when_shown ¤

    (bool, default: True ) –

    Whether field is required when visible. Defaults to True.

Example

Boolean condition¤

web_search_engine: Annotated[ str, Conditional(trigger="web_search_enabled", show_when=True), ] = Field(...)

Enum condition¤

advanced_option: Annotated[ str, Conditional(trigger="mode", show_when="advanced"), ] = Field(...)

Multiple values condition¤

shared_feature: Annotated[ bool, Conditional(trigger="mode", show_when=["standard", "advanced"]), ] = Field(...)

Methods:

  • __post_init__

    Normalize single-item lists to scalar values.

__post_init__ ¤

__post_init__() -> None

Normalize single-item lists to scalar values.

ConditionalSchemaMixin ¤


              flowchart TD
              digitalkin.utils.ConditionalSchemaMixin[ConditionalSchemaMixin]

              

              click digitalkin.utils.ConditionalSchemaMixin href "" "digitalkin.utils.ConditionalSchemaMixin"
            

Mixin for automatic conditional field processing in JSON schema.

Inherit from this mixin to automatically generate JSON Schema with if/then clauses for fields marked with ConditionalField metadata.

The mixin processes Annotated fields with Conditional metadata and: 1. Removes conditional fields from main properties 2. Adds them to allOf with if/then clauses 3. Groups multiple fields with the same condition together

Example

class Config(ConditionalSchemaMixin, BaseModel): mode: Literal["basic", "advanced"] = Field(...)

advanced_option: Annotated[
    str,
    Conditional(trigger="mode", show_when="advanced"),
] = Field(...)

Generates schema with:¤

{¤

"properties": {"mode": {...}},¤

"allOf": [{¤

"if": {"properties": {"mode": {"const": "advanced"}}},¤

"then": {"properties": {"advanced_option": {...}}}¤

}]¤

}¤

Methods:

__get_pydantic_json_schema__ classmethod ¤

__get_pydantic_json_schema__(
    core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue

Generate JSON schema with conditional field handling.

Parameters:

  • core_schema ¤
    (CoreSchema) –

    The Pydantic core schema.

  • handler ¤
    (GetJsonSchemaHandler) –

    The JSON schema handler for resolving refs.

Returns:

  • JsonSchemaValue

    The JSON schema with if/then clauses for conditional fields.

DynamicField ¤

DynamicField(**fetchers: Fetcher[Any])

Metadata class for Annotated fields with dynamic fetchers.

Use with typing.Annotated to mark fields that need runtime value resolution. Fetchers are callables (sync or async) that return values at runtime.

Parameters:

  • **fetchers ¤

    (Fetcher[Any], default: {} ) –

    Mapping of key names to fetcher callables. Each fetcher is a function (sync or async) that takes no arguments and returns the value for that key (e.g., enum values, defaults).

Example

from typing import Annotated

async def fetch_models() -> list[str]: return await api.get_models()

class Setup(SetupModel): model: Annotated[str, DynamicField(enum=fetch_models)] = Field(default="gpt-4")

Methods:

  • __eq__

    Check equality based on fetchers.

  • __hash__

    Hash based on fetcher keys (fetchers themselves aren't hashable).

  • __repr__

    Return string representation.

__eq__ ¤

__eq__(other: object) -> bool

Check equality based on fetchers.

Returns:

  • bool

    True if fetchers are equal, NotImplemented for non-DynamicField types.

__hash__ ¤

__hash__() -> int

Hash based on fetcher keys (fetchers themselves aren't hashable).

Returns:

  • int

    Hash value based on sorted fetcher keys.

__repr__ ¤

__repr__() -> str

Return string representation.

ResolveResult dataclass ¤

ResolveResult(values: dict[str, Any] = dict(), errors: dict[str, Exception] = dict())

Result of resolving dynamic fetchers.

Provides structured access to resolved values and any errors that occurred. This allows callers to handle partial failures gracefully.

Attributes:

  • values (dict[str, Any]) –

    Dict mapping key names to successfully resolved values.

  • errors (dict[str, Exception]) –

    Dict mapping key names to exceptions that occurred during resolution.

Methods:

  • get

    Get a resolved value by key.

partial property ¤

partial: bool

Check if some but not all fetchers succeeded.

Returns:

  • bool

    True if there are both values and errors, False otherwise.

success property ¤

success: bool

Check if all fetchers resolved successfully.

Returns:

  • bool

    True if no errors occurred, False otherwise.

get ¤

get(key: str, default: T | None = None) -> T | None

Get a resolved value by key.

Parameters:

  • key ¤
    (str) –

    The fetcher key name.

  • default ¤
    (T | None, default: None ) –

    Default value if key not found or errored.

Returns:

  • T | None

    The resolved value or default.

get_conditional_metadata ¤

get_conditional_metadata(field_info: FieldInfo) -> ConditionalField | None

Extract ConditionalField from field metadata.

Parameters:

  • field_info ¤

    (FieldInfo) –

    The Pydantic FieldInfo object to inspect.

Returns:

  • ConditionalField | None

    The ConditionalField metadata instance if found, None otherwise.

get_dynamic_metadata ¤

get_dynamic_metadata(field_info: FieldInfo) -> DynamicField | None

Extract DynamicField metadata from a FieldInfo's metadata list.

Parameters:

  • field_info ¤

    (FieldInfo) –

    The Pydantic FieldInfo object to inspect.

Returns:

  • DynamicField | None

    The DynamicField metadata instance if found, None otherwise.

get_fetchers ¤

get_fetchers(field_info: FieldInfo) -> dict[str, Fetcher[Any]]

Extract fetchers from a field's DynamicField metadata.

Parameters:

  • field_info ¤

    (FieldInfo) –

    The Pydantic FieldInfo object to extract from.

Returns:

  • dict[str, Fetcher[Any]]

    Dict mapping key names to fetcher callables, empty if no DynamicField metadata.

has_conditional ¤

has_conditional(field_info: FieldInfo) -> bool

Check if field has ConditionalField metadata.

Parameters:

  • field_info ¤

    (FieldInfo) –

    The Pydantic FieldInfo object to check.

Returns:

  • bool

    True if the field has ConditionalField metadata, False otherwise.

has_dynamic ¤

has_dynamic(field_info: FieldInfo) -> bool

Check if a field has DynamicField metadata.

Parameters:

  • field_info ¤

    (FieldInfo) –

    The Pydantic FieldInfo object to check.

Returns:

  • bool

    True if the field has DynamicField metadata, False otherwise.

resolve async ¤

resolve(
    fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> dict[str, Any]

Resolve all dynamic fetchers to their actual values in parallel.

Fetchers are executed concurrently using asyncio.gather() for better performance when multiple async fetchers are involved.

Parameters:

  • fetchers ¤

    (dict[str, Fetcher[Any]]) –

    Dict mapping key names to fetcher callables.

  • timeout ¤

    (float | None, default: DEFAULT_TIMEOUT ) –

    Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied.

Returns:

  • dict[str, Any]

    Dict mapping key names to resolved values.

Raises:

  • TimeoutError

    If timeout is exceeded.

  • Exception

    If any fetcher raises an exception, it is propagated.

Example

fetchers = {"enum": fetch_models, "default": get_default} resolved = await resolve(fetchers, timeout=5.0)

resolved =¤

resolve_safe async ¤

resolve_safe(
    fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> ResolveResult

Resolve fetchers with structured error handling.

Unlike resolve(), this function catches individual fetcher errors and returns them in a structured result, allowing partial success.

Parameters:

  • fetchers ¤

    (dict[str, Fetcher[Any]]) –

    Dict mapping key names to fetcher callables.

  • timeout ¤

    (float | None, default: DEFAULT_TIMEOUT ) –

    Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied. Note: timeout applies to the entire operation, not individual fetchers.

Returns:

  • ResolveResult

    ResolveResult with values and any errors that occurred.

Example

result = await resolve_safe(fetchers, timeout=5.0) if result.success: print("All resolved:", result.values) elif result.partial: print("Partial success:", result.values) print("Errors:", result.errors) else: print("All failed:", result.errors)

arg_parser ¤

ArgParser and Action classes to ease command lines arguments settings.

Classes:

  • ArgParser

    ArgParse Abstract class to join all argparse argument in the same parser.

ArgParser ¤

ArgParser(prog: str = 'PROG')

ArgParse Abstract class to join all argparse argument in the same parser.

Custom help display to allow multiple parser and subparser help message.

Examples:¤

Inherit this class in your base class. Override '_add_parser_args', '_add_exclusive_args' and '_add_subparser_args'.

class WindowHandler(ArgParser):

@staticmethod
def _add_screen_parser_args(parser) -> None:
    parser.add_argument(
        "-f", "--fps", type=int, default=60, help="Screen FPS", dest="fps"
    )

def _add_media_parser_args(self, parser) -> None:
    parser.add_argument(
        "-w",
        "--workers",
        type=int,
        default=3,
        help="Number of worker processing media in background",
        dest="media_worker_count"
    )

def _add_parser_args(self, parser) -> None:
    super()._add_parser_args(parser)
    self._add_screen_parser_args(parser)
    self._add_media_parser_args(parser)

def __init__(self):
    # init the parser
    super().__init__()

Classes:

  • HelpAction

    Custom HelpAction to display subparsers helps too.

Attributes:

args instance-attribute ¤
args: Namespace

Override methods

HelpAction ¤

              flowchart TD
              digitalkin.utils.arg_parser.ArgParser.HelpAction[HelpAction]

              

              click digitalkin.utils.arg_parser.ArgParser.HelpAction href "" "digitalkin.utils.arg_parser.ArgParser.HelpAction"
            

Custom HelpAction to display subparsers helps too.

Methods:

  • __call__

    Override the HelpActions as it doesn't handle subparser well.

__call__ ¤
__call__(
    parser: ArgumentParser,
    namespace: Namespace,
    values: str | Sequence[Any] | None,
    option_string: str | None = None,
) -> None

Override the HelpActions as it doesn't handle subparser well.

conditional_schema ¤

Conditional field visibility for react-jsonschema-form.

This module provides a clean way to mark fields as conditional using Annotated metadata, generating JSON Schema with if/then clauses for react-jsonschema-form.

Example

from typing import Annotated, Literal from pydantic import BaseModel, Field from digitalkin.utils import Conditional, ConditionalSchemaMixin

class Tools(ConditionalSchemaMixin, BaseModel): web_search_enabled: bool = Field(...)

web_search_engine: Annotated[
    Literal["duckduckgo", "tavily"],
    Conditional(trigger="web_search_enabled", show_when=True),
] = Field(...)
See Also
  • Documentation: docs/api/conditional_schema.md
  • Tests: tests/utils/test_conditional_schema.py

Classes:

Functions:

ConditionalField dataclass ¤

ConditionalField(
    trigger: str, show_when: bool | str | list[str], required_when_shown: bool = True
)

Metadata for conditional field visibility.

Use with typing.Annotated to mark fields that should only appear when a trigger field has a specific value.

Parameters:

  • trigger ¤
    (str) –

    Name of the field that controls visibility.

  • show_when ¤
    (bool | str | list[str]) –

    Value(s) that trigger field must have to show this field. Can be a boolean, string, or list of strings for multiple values.

  • required_when_shown ¤
    (bool, default: True ) –

    Whether field is required when visible. Defaults to True.

Example
Boolean condition¤

web_search_engine: Annotated[ str, Conditional(trigger="web_search_enabled", show_when=True), ] = Field(...)

Enum condition¤

advanced_option: Annotated[ str, Conditional(trigger="mode", show_when="advanced"), ] = Field(...)

Multiple values condition¤

shared_feature: Annotated[ bool, Conditional(trigger="mode", show_when=["standard", "advanced"]), ] = Field(...)

Methods:

  • __post_init__

    Normalize single-item lists to scalar values.

__post_init__ ¤
__post_init__() -> None

Normalize single-item lists to scalar values.

ConditionalSchemaMixin ¤


              flowchart TD
              digitalkin.utils.conditional_schema.ConditionalSchemaMixin[ConditionalSchemaMixin]

              

              click digitalkin.utils.conditional_schema.ConditionalSchemaMixin href "" "digitalkin.utils.conditional_schema.ConditionalSchemaMixin"
            

Mixin for automatic conditional field processing in JSON schema.

Inherit from this mixin to automatically generate JSON Schema with if/then clauses for fields marked with ConditionalField metadata.

The mixin processes Annotated fields with Conditional metadata and: 1. Removes conditional fields from main properties 2. Adds them to allOf with if/then clauses 3. Groups multiple fields with the same condition together

Example

class Config(ConditionalSchemaMixin, BaseModel): mode: Literal["basic", "advanced"] = Field(...)

advanced_option: Annotated[
    str,
    Conditional(trigger="mode", show_when="advanced"),
] = Field(...)
Generates schema with:¤
{¤
"properties": {"mode": {...}},¤
"allOf": [{¤
"if": {"properties": {"mode": {"const": "advanced"}}},¤
"then": {"properties": {"advanced_option": {...}}}¤
}]¤
}¤

Methods:

__get_pydantic_json_schema__ classmethod ¤
__get_pydantic_json_schema__(
    core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue

Generate JSON schema with conditional field handling.

Parameters:

  • core_schema ¤
    (CoreSchema) –

    The Pydantic core schema.

  • handler ¤
    (GetJsonSchemaHandler) –

    The JSON schema handler for resolving refs.

Returns:

  • JsonSchemaValue

    The JSON schema with if/then clauses for conditional fields.

get_conditional_metadata ¤

get_conditional_metadata(field_info: FieldInfo) -> ConditionalField | None

Extract ConditionalField from field metadata.

Parameters:

  • field_info ¤
    (FieldInfo) –

    The Pydantic FieldInfo object to inspect.

Returns:

  • ConditionalField | None

    The ConditionalField metadata instance if found, None otherwise.

has_conditional ¤

has_conditional(field_info: FieldInfo) -> bool

Check if field has ConditionalField metadata.

Parameters:

  • field_info ¤
    (FieldInfo) –

    The Pydantic FieldInfo object to check.

Returns:

  • bool

    True if the field has ConditionalField metadata, False otherwise.

development_mode_action ¤

ArgParser and Action classes to ease command lines arguments settings.

Classes:

DevelopmentModeMappingAction ¤

DevelopmentModeMappingAction(
    env_var: str, required: bool = True, default: str | None = None, **kwargs: Any
)

              flowchart TD
              digitalkin.utils.development_mode_action.DevelopmentModeMappingAction[DevelopmentModeMappingAction]

              

              click digitalkin.utils.development_mode_action.DevelopmentModeMappingAction href "" "digitalkin.utils.development_mode_action.DevelopmentModeMappingAction"
            

ArgParse Action to map an environment variable to a ServicesMode enum.

Methods:

  • __call__

    Set the attribute to the corresponding class.

__call__ ¤
__call__(
    parser: ArgumentParser,
    namespace: Namespace,
    values: str | Sequence[Any] | None,
    option_string: str | None = None,
) -> None

Set the attribute to the corresponding class.

Raises:

  • TypeError

    if the value is not a string.

dynamic_schema ¤

Dynamic schema utilities for runtime value refresh in Pydantic models.

This module provides a clean way to mark fields as dynamic using Annotated metadata, allowing their schema values to be refreshed at runtime via sync or async fetchers.

Example

from typing import Annotated from digitalkin.utils import DynamicField

class AgentSetup(SetupModel): model_name: Annotated[str, DynamicField(enum=fetch_models)] = Field(default="gpt-4")

See Also
  • Documentation: docs/api/dynamic_schema.md
  • Tests: tests/utils/test_dynamic_schema.py

Classes:

  • DynamicField

    Metadata class for Annotated fields with dynamic fetchers.

  • ResolveResult

    Result of resolving dynamic fetchers.

Functions:

  • get_dynamic_metadata

    Extract DynamicField metadata from a FieldInfo's metadata list.

  • get_fetchers

    Extract fetchers from a field's DynamicField metadata.

  • has_dynamic

    Check if a field has DynamicField metadata.

  • resolve

    Resolve all dynamic fetchers to their actual values in parallel.

  • resolve_safe

    Resolve fetchers with structured error handling.

DynamicField ¤

DynamicField(**fetchers: Fetcher[Any])

Metadata class for Annotated fields with dynamic fetchers.

Use with typing.Annotated to mark fields that need runtime value resolution. Fetchers are callables (sync or async) that return values at runtime.

Parameters:

  • **fetchers ¤
    (Fetcher[Any], default: {} ) –

    Mapping of key names to fetcher callables. Each fetcher is a function (sync or async) that takes no arguments and returns the value for that key (e.g., enum values, defaults).

Example

from typing import Annotated

async def fetch_models() -> list[str]: return await api.get_models()

class Setup(SetupModel): model: Annotated[str, DynamicField(enum=fetch_models)] = Field(default="gpt-4")

Methods:

  • __eq__

    Check equality based on fetchers.

  • __hash__

    Hash based on fetcher keys (fetchers themselves aren't hashable).

  • __repr__

    Return string representation.

__eq__ ¤
__eq__(other: object) -> bool

Check equality based on fetchers.

Returns:

  • bool

    True if fetchers are equal, NotImplemented for non-DynamicField types.

__hash__ ¤
__hash__() -> int

Hash based on fetcher keys (fetchers themselves aren't hashable).

Returns:

  • int

    Hash value based on sorted fetcher keys.

__repr__ ¤
__repr__() -> str

Return string representation.

ResolveResult dataclass ¤

ResolveResult(values: dict[str, Any] = dict(), errors: dict[str, Exception] = dict())

Result of resolving dynamic fetchers.

Provides structured access to resolved values and any errors that occurred. This allows callers to handle partial failures gracefully.

Attributes:

  • values (dict[str, Any]) –

    Dict mapping key names to successfully resolved values.

  • errors (dict[str, Exception]) –

    Dict mapping key names to exceptions that occurred during resolution.

Methods:

  • get

    Get a resolved value by key.

partial property ¤
partial: bool

Check if some but not all fetchers succeeded.

Returns:

  • bool

    True if there are both values and errors, False otherwise.

success property ¤
success: bool

Check if all fetchers resolved successfully.

Returns:

  • bool

    True if no errors occurred, False otherwise.

get ¤
get(key: str, default: T | None = None) -> T | None

Get a resolved value by key.

Parameters:

  • key ¤
    (str) –

    The fetcher key name.

  • default ¤
    (T | None, default: None ) –

    Default value if key not found or errored.

Returns:

  • T | None

    The resolved value or default.

get_dynamic_metadata ¤

get_dynamic_metadata(field_info: FieldInfo) -> DynamicField | None

Extract DynamicField metadata from a FieldInfo's metadata list.

Parameters:

  • field_info ¤
    (FieldInfo) –

    The Pydantic FieldInfo object to inspect.

Returns:

  • DynamicField | None

    The DynamicField metadata instance if found, None otherwise.

get_fetchers ¤

get_fetchers(field_info: FieldInfo) -> dict[str, Fetcher[Any]]

Extract fetchers from a field's DynamicField metadata.

Parameters:

  • field_info ¤
    (FieldInfo) –

    The Pydantic FieldInfo object to extract from.

Returns:

  • dict[str, Fetcher[Any]]

    Dict mapping key names to fetcher callables, empty if no DynamicField metadata.

has_dynamic ¤

has_dynamic(field_info: FieldInfo) -> bool

Check if a field has DynamicField metadata.

Parameters:

  • field_info ¤
    (FieldInfo) –

    The Pydantic FieldInfo object to check.

Returns:

  • bool

    True if the field has DynamicField metadata, False otherwise.

resolve async ¤

resolve(
    fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> dict[str, Any]

Resolve all dynamic fetchers to their actual values in parallel.

Fetchers are executed concurrently using asyncio.gather() for better performance when multiple async fetchers are involved.

Parameters:

  • fetchers ¤
    (dict[str, Fetcher[Any]]) –

    Dict mapping key names to fetcher callables.

  • timeout ¤
    (float | None, default: DEFAULT_TIMEOUT ) –

    Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied.

Returns:

  • dict[str, Any]

    Dict mapping key names to resolved values.

Raises:

  • TimeoutError

    If timeout is exceeded.

  • Exception

    If any fetcher raises an exception, it is propagated.

Example

fetchers = {"enum": fetch_models, "default": get_default} resolved = await resolve(fetchers, timeout=5.0)

resolved =¤

resolve_safe async ¤

resolve_safe(
    fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> ResolveResult

Resolve fetchers with structured error handling.

Unlike resolve(), this function catches individual fetcher errors and returns them in a structured result, allowing partial success.

Parameters:

  • fetchers ¤
    (dict[str, Fetcher[Any]]) –

    Dict mapping key names to fetcher callables.

  • timeout ¤
    (float | None, default: DEFAULT_TIMEOUT ) –

    Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied. Note: timeout applies to the entire operation, not individual fetchers.

Returns:

  • ResolveResult

    ResolveResult with values and any errors that occurred.

Example

result = await resolve_safe(fetchers, timeout=5.0) if result.success: print("All resolved:", result.values) elif result.partial: print("Partial success:", result.values) print("Errors:", result.errors) else: print("All failed:", result.errors)

llm_ready_schema ¤

LLM format schema for Pydantic models.

This module provides functionality to generate JSON schemas for Pydantic models ready for LLMs.

Classes:

Functions:

  • inline_refs

    Recursively resolve and inline all $ref in the schema.

  • llm_ready_schema

    Convert a Pydantic model to a JSON schema ready for LLMs.

CustomOrderSchema ¤


              flowchart TD
              digitalkin.utils.llm_ready_schema.CustomOrderSchema[CustomOrderSchema]

              

              click digitalkin.utils.llm_ready_schema.CustomOrderSchema href "" "digitalkin.utils.llm_ready_schema.CustomOrderSchema"
            

Custom schema generator to sort keys in a specific order.

Methods:

  • sort

    Sort the keys of the schema in a specific order.

sort ¤
sort(value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue

Sort the keys of the schema in a specific order.

Parameters:

  • value ¤
    (JsonSchemaValue) –

    The schema value to sort.

  • parent_key ¤
    (str | None, default: None ) –

    The parent key of the schema value.

Returns:

  • JsonSchemaValue

    The sorted schema value.

inline_refs ¤

inline_refs(schema: dict) -> dict

Recursively resolve and inline all $ref in the schema.

Parameters:

  • schema ¤
    (dict) –

    The JSON schema to inline.

Returns:

  • dict

    The inlined JSON schema.

llm_ready_schema ¤

llm_ready_schema(model: type[BaseModel]) -> dict

Convert a Pydantic model to a JSON schema ready for LLMs.

Parameters:

  • model ¤
    (type[BaseModel]) –

    The Pydantic model to convert.

Returns:

  • dict

    The JSON schema as a dictionary.

package_discover ¤

Secure module discovery and import utility for trigger handlers.

Classes:

  • DiscoveryError

    Raised when discovery fails due to invalid inputs.

  • ModuleDiscoverer

    Encapsulates secure, structured discovery and import of trigger modules.

  • SecurityError

    Raised when security constraints are violated.

DiscoveryError ¤


              flowchart TD
              digitalkin.utils.package_discover.DiscoveryError[DiscoveryError]

              

              click digitalkin.utils.package_discover.DiscoveryError href "" "digitalkin.utils.package_discover.DiscoveryError"
            

Raised when discovery fails due to invalid inputs.

ModuleDiscoverer ¤

ModuleDiscoverer(
    packages: list[str],
    file_pattern: str = "*_trigger.py",
    max_file_size: int = 1024 * 1024,
)

Encapsulates secure, structured discovery and import of trigger modules.

Attributes:

  • packages

    List of Python package paths to scan.

  • file_pattern

    Glob pattern to match module filenames.

  • safe_mode

    If True, skips unsafe imports.

  • max_file_size

    Maximum file size allowed for import (bytes).

Parameters:

  • packages ¤
    (list[str]) –

    List of package names to scan.

  • file_pattern ¤
    (str, default: '*_trigger.py' ) –

    Glob pattern for matching modules.

  • max_file_size ¤
    (int, default: 1024 * 1024 ) –

    Limit for module file sizes in bytes.

Methods:

  • __str__

    Return a string representation of registered trigger handler classes.

  • discover_modules

    Discover and import matching modules across configured packages.

  • get_registered_protocols_with_info

    Get registered protocols with their descriptions.

  • get_trigger

    Retrieve a trigger handler instance based on the provided protocol and input instance type.

  • init_handlers

    Instantiate all registered trigger handler classes.

  • register_trigger

    Register a trigger handler class for a specific protocol.

__str__ ¤
__str__() -> str

Return a string representation of registered trigger handler classes.

discover_modules ¤
discover_modules() -> dict[str, bool]

Discover and import matching modules across configured packages.

Returns:

Raises:

get_registered_protocols_with_info ¤
get_registered_protocols_with_info(*, exclude_utility: bool = False) -> dict[str, str]

Get registered protocols with their descriptions.

Parameters:

  • exclude_utility ¤
    (bool, default: False ) –

    If True, exclude SDK utility protocols (healthcheck, etc.).

Returns:

  • dict[str, str]

    Dict mapping protocol name to description (from handler description attribute).

get_trigger staticmethod ¤

Retrieve a trigger handler instance based on the provided protocol and input instance type.

Parameters:

  • handlers ¤
    (dict[str, tuple[TriggerHandler, ...]]) –

    Mapping of protocol name to handler instance tuples.

  • protocol ¤
    (str) –

    The protocol name (ignored internally, input_instance.protocol is used instead).

  • input_instance ¤
    (DataTrigger) –

    The input trigger instance used to determine the correct handler.

Returns:

  • TriggerHandler ( TriggerHandler ) –

    An instance of the trigger handler matching the input format.

Raises:

  • ValueError

    If no handler is registered for the specified protocol, or if no handler matches the type of the input instance.

init_handlers ¤
init_handlers(context: ModuleContext) -> dict[str, tuple[TriggerHandler, ...]]

Instantiate all registered trigger handler classes.

Parameters:

  • context ¤
    (ModuleContext) –

    Module context to pass to each handler constructor.

Returns:

register_trigger ¤

Register a trigger handler class for a specific protocol.

Parameters:

Returns:

Raises:

  • ValueError

    If a handler for the protocol is already registered.

SecurityError ¤


              flowchart TD
              digitalkin.utils.package_discover.SecurityError[SecurityError]

              

              click digitalkin.utils.package_discover.SecurityError href "" "digitalkin.utils.package_discover.SecurityError"
            

Raised when security constraints are violated.

proto_utils ¤

Protobuf conversion utilities.

Functions:

  • proto_to_dict

    Convert a protobuf message to a dict preserving snake_case field names.

proto_to_dict ¤

proto_to_dict(msg: Message, *, with_defaults: bool = False) -> dict

Convert a protobuf message to a dict preserving snake_case field names.

Parameters:

  • msg ¤
    (Message) –

    Protobuf message to convert.

  • with_defaults ¤
    (bool, default: False ) –

    If True, include fields with default/zero values.

Returns:

  • dict

    Dictionary representation with original field names preserved.

schema_splitter ¤

Schema splitter for react-jsonschema-form.

Classes:

  • SchemaSplitter

    Splits a combined JSON schema into jsonschema and uischema for react-jsonschema-form.

SchemaSplitter ¤

Splits a combined JSON schema into jsonschema and uischema for react-jsonschema-form.

Methods:

  • split

    Split schema into (jsonschema, uischema).

split classmethod ¤

Split schema into (jsonschema, uischema).

Parameters:

  • combined_schema ¤
    (dict[str, Any]) –

    Combined JSON schema with ui:* properties.

Returns: