Skip to content

unaiverse.hsm.action

This module holds Action and ActionInteractionList. An Action binds one method of an agent to a transition (or to a state) of a HybridStateMachine together with the arguments written in the behavior, the readiness flags, the three timing limits and the queue of the requests that other agents sent for it. ActionInteractionList is that queue. The machine creates both. add_transit() and add_state() build one Action per transition or state and request_action() appends to the queue of the matching action. A developer meets Action objects in custom policies and filters because both receive the list of feasible actions (see Policies). The concepts behind actions are in Actions and the requests are described in Interactions.

The @action decorator

The methods that an Action wraps are the async methods of an agent marked with @action. The decorator lives in unaiverse.agent and fixes the contract that Action relies on.

  • The method is async and returns a truth value. Action treats every truthy value as success and every falsy value (False, 0, "", []) as failure.
  • A method that returns None is logged as an error and counts as False.
  • An exception raised by the method is logged with its traceback and counts as False. The machine and the node keep running.
  • Before the call the decorator resolves the arguments named agent, agents, partner, partners, target and targets from node names to peer ids and the arguments named stream and streams from stream names to net hashes (see Custom.AGENT_ARG_NAMES and Custom.STREAM_ARG_NAMES). The action send is excluded because it resolves its own arguments.
  • A parameter named interaction receives the Interaction that the call serves. Its presence also makes the transition request-only unless the behavior says "ready": true explicitly.
from unaiverse.agent import Agent, action

class Referee(Agent):

    @action
    async def start_match(self, players: int = 2, interaction=None) -> bool:
        if len(self.world_agents) < players:
            return False  # the machine retries or moves on, depending on retry_timeout
        return True

Return codes

The machine awaits an action as await action(interaction) and receives one of four integer codes. Called without an argument, the action serves its own system interaction. This is how the machine runs an action on the initiative of the agent. An interaction is single-step when its num_steps is 1 or negative (the default -1 means no data stream) and multi-step when num_steps is greater than 1 or still a wildcard string. A multi-step interaction runs the method once per data sample. The call goes through these steps:

  1. The arguments are built from three sources in decreasing priority: (1) the arguments of the transition, (2) the arguments of the interaction after the replacement of the wildcards and (3) the defaults of the method. A value written in the behavior therefore wins over the value of a request. A parameter missing from all three sources is logged and raises AssertionError.
  2. At the first attempt the call prints the message of the action and records the starting time of the interaction. A pedantic single-step action also starts its retry timer at this point.
  3. When the interaction has timed out, the call returns without running the method. The interaction times out when max_duration seconds have passed since its first attempt or retry_timeout seconds have passed since the last successful step. A single-step action returns 2. A multi-step action returns 0 when at least one step was done and 2 otherwise.
  4. After its first step, a multi-step action returns 1 without running the method as long as one of its streams lacks fresh data.
  5. The method runs with the parameter interaction filled when the method declares it.
  6. A falsy result gives the codes of the first table below and a truthy result the codes of the second one.
Falsy result Pedantic (retry_timeout > 0) Not pedantic
single-step 1 2
multi-step, no step done yet 2 2
multi-step, at least one step done 1 0
Truthy result Code
single-step 0
multi-step, last step done 0
multi-step, more steps to go 1

0 completes the transition, 1 keeps the machine on this action and 2 discards the attempt (see the codes in the machine). An interaction with num_steps equal to 0 is neither single-step nor multi-step and the call returns -1. A successful step restarts the retry timer and records the data tags that the step consumed. When a multi-step interaction without retry_timeout is bound to the action, the action receives Custom.DEFAULT_TIMEOUT (10 seconds) as retry window and becomes pedantic.

Action

Action(name: str, args: dict, agent: AgentBasics, idx: int = -1, ready: bool = True, msg: str | None = None, avoid_changing_ready: bool = False, teleport: bool = False, high_priority: bool = False, max_duration: float | str = 0.0, retry_timeout: float | str = 0, delay: float | str = 0)
Source code in unaiverse/hsm/action.py
def __init__(self, name: str, args: dict, agent: "AgentBasics",
             idx: int = -1,
             ready: bool = True,
             msg: str | None = None,
             avoid_changing_ready: bool = False,
             teleport: bool = False,
             high_priority: bool = False,
             max_duration: float | str = 0.,
             retry_timeout: float | str = 0,
             delay: float | str = 0):
    """Initializes an `Action` object, which encapsulates a method to be executed on a given object (`agent`)
    with specified arguments. It sets up various properties for managing multistep actions, including
    `total_steps`, `total_time`, and `retry_timeout`. It also handles wildcard argument replacement and checks for
    existence of required parameters. It identifies if the action is a 'not ready' type (e.g., `do_`, `get_`) and
    sets its initial status accordingly.

    Args:
        name: The name of the method to call.
        args: A dictionary of arguments for the method.
        agent: The object on which the method will be executed.
        idx: A unique ID for the Custom.
        ready: A boolean indicating if the action is ready to be executed.
        msg: An optional human-readable message.
        avoid_changing_ready: A boolean indicating that the selected ready state should not be changed by
            internal rules.
        teleport: A boolean indicating that this action must be hidden when drawing the state machine ('teleport').
        high_priority: A boolean indicating that this action must be preferred over others by the policy.
        max_duration: The number of seconds representing the max duration of this action (from when it starts).
            When <= 0., then no limits. It can be a wildcard (str).
        retry_timeout: The number of seconds representing the max time we keep try running this action before
            giving up. When <= 0., then no timeouts at all. It can be a wildcard (str).
        delay: The number of seconds that must pass when joining a state before considering this action.
            When <= 0., then no delays at all. It can be a wildcard (str).
    """
    # Basic properties
    self.name = name  # Name of the action (name of the corresponding method)
    self.args = args.copy()  # Dictionary of arguments to pass to the action (shallow copy, we will remove some)
    self.agent: "AgentBasics" = agent  # Object on which the method whose name is self.name is searched
    self.interactions: ActionInteractionList = ActionInteractionList()  # List of interactions
    self.id = idx  # Unique ID of the action (-1 if not needed)
    self.msg = msg  # Human-readable message associated to this instance of action
    self.inner = ready
    self.outer = True
    self.state_machine = None
    self.teleport = teleport
    self.high_priority = high_priority
    self.__mark = None

    # Who the message was last printed for (None: nobody), so that the retries of a failing action print it once
    self.__msg_printed_for: str | None = None

    # Fix UNICODE chars
    if self.msg is not None:
        self.msg = html.unescape(self.msg)

    # Reference elements
    assert self.agent is not None
    self.__fcn = self.__action_name_to_callable(name)  # The real method to be called
    self.__sig = inspect.signature(self.__fcn)  # Signature of the method for argument inspection

    # Parameter names and default values
    self.param_list = []  # Full list of the parameters that the action supports
    self.param_to_default_value = {}  # From parameter to its default value, if any
    self.__get_action_params()  # This will fill the two attributes above

    # Time-based metrics
    self.__action_max_duration = max_duration  # A total time <= 0 means "no total time at all"
    self.__action_max_duration_with_wildcard = max_duration if isinstance(max_duration, str) else None
    self.__guess_total_time(self.args)  # This will "guess" the value of self.__action_max_duration from args dict

    # Time-based metrics
    self.__action_retry_timeout = retry_timeout  # A retry_timeout <= 0 means "no total time at all"
    self.__action_retry_timeout_with_wildcard = retry_timeout if isinstance(retry_timeout, str) else None
    self.__guess_timeout(self.args)  # This will "guess" the value of self.__action_retry_timeout from the args dict
    self.__action_pedantic_by_default = (
        self.is_pedantic()) if not isinstance(self.__action_retry_timeout, str) else False

    # Time-based metrics
    self.__delay = delay
    self.__delay_with_wildcard = delay if isinstance(delay, str) else None
    self.__guess_delay(self.args)  # This will "guess" the value of self.__delay from the args dict

    # Checking arguments (also removing 'retry_timeout', 'delay', etc...)
    self.check_provided_args(self.args, exception=True, remove_special_arguments=True)

    # Argument values replaced by wildcards (commonly assumed to be in the format <value>)
    self.wildcards = {}  # Value-to-value (es: <playlist> to this:and:this)
    self.args_with_wildcards = copy.deepcopy(self.args)  # Backup of the originally provided arguments
    self.msg_with_wildcards = self.msg

    # Fixing (forcing NOT-ready on some actions)
    if not avoid_changing_ready:
        for p in self.param_list:
            if p in Custom.INTERACTION_INJECT_NAMES:
                self.inner = False
                self.outer = True
                break

    # Whether for this Action we've already register_lazy a system_interaction,
    # and whether `copy_sys` was requested for the current round.
    self._lazy_registered = False
    self._must_lazy_register = False
    self._copy_sys_on_register = False

    # Build the initial system_interaction (lightweight dummy or interaction-shaped). MUST stay
    # at the very end of __init__.
    self.__build_system_interaction()

The binding of one method of an agent to a transition or a state. The machine creates it.

Argument Type Default Meaning
name str required The name of the method. It is resolved on agent with getattr and a missing method raises AttributeError.
args dict required The arguments written in the behavior. The object keeps a shallow copy.
agent AgentBasics required The object that owns the method.
idx int -1 The numeric id of the action in the machine.
ready bool True The inner readiness: whether the action can run on the initiative of the agent.
msg str \| None None The message printed at the first attempt. HTML entities are decoded.
avoid_changing_ready bool False With False an action whose method declares a parameter named interaction becomes request-only whatever ready says.
teleport bool False Whether the action labels a teleport.
high_priority bool False Whether the default policy prefers it.
max_duration float \| str 0. The maximum life in seconds since the first attempt. A value of 0 or less means no limit and a string is a wildcard.
retry_timeout float \| str 0 The retry window in seconds since the last successful step. A value greater than 0 makes the action pedantic and a string is a wildcard.
delay float \| str 0 The seconds after entering the source state before the action becomes feasible. A string is a wildcard.

The constructor processes the arguments in this order:

  1. It inspects the signature of the method. A parameter named max_duration, retry_timeout or delay (or action_kwargs in any method other than send) raises GenException.
  2. It reads max_duration, retry_timeout and delay from args when present. These values override the constructor arguments and are removed from args. A numeric value below 0 becomes 0 and a non-numeric string is kept as a wildcard.
  3. It validates args with check_provided_args(exception=True). The keys interaction and action_kwargs raise ValueError like any key that is neither a parameter of the method nor an interaction field.
  4. It makes the action request-only when the method declares interaction and avoid_changing_ready is False.
  5. It builds the system interaction. Each key of args that is an interaction field (see Custom.INTERACTION_FIELD_NAMES) and not a parameter of the method moves from the arguments to the system interaction. The system interaction is registered with the interaction manager of the agent at the first call when it carries streams, data samples or num_steps greater than 0. When the field copy_sys is True, the registration also copies into each stream of the interaction the last sample stored under the UUID of the system interaction.
Attribute Type Meaning
name, id, agent, teleport, high_priority The constructor arguments.
args dict The arguments of the behavior after the replacement of the wildcards. The timing keys and the interaction fields are not part of it.
args_with_wildcards dict A deep copy of the arguments as written in the behavior.
msg, msg_with_wildcards str \| None The message after and before the replacement of the wildcards.
inner bool The inner readiness (the JSON field ready).
outer bool Whether the action accepts requests from other agents. It starts True.
interactions ActionInteractionList The pending requests.
param_list list[str] The parameter names of the method in signature order.
param_to_default_value dict The default values of the parameters that have one.
system_interaction Interaction The interaction served when the action runs on the initiative of the agent.
wildcards dict The same dictionary object that holds the wildcards of the machine.
state_machine HybridStateMachine \| None The owner machine.

Readiness

ready property

ready: bool

A read-only property that returns the inner readiness inner of the action.

is_ready

is_ready(consider_interactions: bool = True, delay_starting_time: float = -1.0) -> bool
Source code in unaiverse/hsm/action.py
def is_ready(self, consider_interactions: bool = True, delay_starting_time: float = -1.) -> bool:
    """Checks if the action is ready to be executed. It returns `True` if the `ready` flag is set or if there are
    any pending interactions.

    Args:
        consider_interactions: A boolean flag to include pending interactions in the readiness check.
        delay_starting_time: The starting time from which the delay is calculated (in seconds).

    Returns:
        A boolean indicating the action's readiness.
    """
    is_delayed = (delay_starting_time > 0 and self.__delay > 0 and
                  (time.perf_counter() - delay_starting_time) <= self.__delay)
    return not is_delayed and (self.inner or (consider_interactions and self.outer and len(
        self.interactions.get_interactions(doable_only=True)) > 0))

Returns True when the action can run now. A delayed action is never ready. The action is delayed when delay_starting_time is positive and no more than delay seconds have passed since then. Outside the delay the action is ready when inner is True or when consider_interactions is True, outer is True and at least one pending interaction can be served now. An interaction can be served when it is not completed, its requester is a known agent and all its streams have fresh data. The machine passes the starting time of the current state as delay_starting_time.

set_as_ready

set_as_ready() -> None
Source code in unaiverse/hsm/action.py
def set_as_ready(self) -> None:
    """Sets the action's ready flag to `True`, indicating it can now be executed."""
    self.outer = False  # For the moment, I prefer to avoid "solid" actions to also take requests from the outside
    self.inner = True

Makes the action ready on its own (inner=True) and stops it from accepting new requests (outer=False). Returns None.

set_as_not_ready

set_as_not_ready() -> None
Source code in unaiverse/hsm/action.py
def set_as_not_ready(self) -> None:
    """Sets the action's ready flag to `False`, preventing it from being executed
        (unless requested from the outside)."""
    self.inner = False
    self.outer = True

Makes the action request-only (inner=False, outer=True). HybridStateMachine.wait_for_all_actions_that_start_with() and wait_for_all_actions_that_include_an_arg() call it. Returns None.

allows_outer_interactions

allows_outer_interactions() -> bool
Source code in unaiverse/hsm/action.py
def allows_outer_interactions(self) -> bool:
    """Returns whether this action can be triggered by external (outer) interactions."""
    return self.outer

Returns outer, the flag that lets the action accept requests from other agents.

allows_inner_interactions

allows_inner_interactions() -> bool
Source code in unaiverse/hsm/action.py
def allows_inner_interactions(self) -> bool:
    """Returns whether this action can be triggered internally (inner readiness flag)."""
    return self.inner

Returns inner, the flag that lets the action run on the initiative of the agent.

is_high_priority property

is_high_priority: bool

A read-only property equal to high_priority.

set_high_priority

set_high_priority() -> None
Source code in unaiverse/hsm/action.py
def set_high_priority(self) -> None:
    self.high_priority = True

Makes the action high-priority. No method turns the flag off again. Returns None.

is_teleport

is_teleport()
Source code in unaiverse/hsm/action.py
def is_teleport(self):
    """Returns whether this action is a 'teleport' action, hidden from the shown state machine."""
    return self.teleport

Returns True when the action labels a teleport.

Timing

get_total_time

get_total_time() -> float | str
Source code in unaiverse/hsm/action.py
def get_total_time(self) -> float | str:
    """Returns the total execution time configured for this action (0 means no limit)."""
    return self.__action_max_duration

Returns max_duration in seconds. A value of 0 or less means no limit and a string is a wildcard not yet replaced.

get_timeout

get_timeout() -> float | str
Source code in unaiverse/hsm/action.py
def get_timeout(self) -> float | str:
    """Returns the retry_timeout configured for this action (0 means no retry_timeout)."""
    return self.__action_retry_timeout

Returns retry_timeout in seconds. A value of 0 or less means no retry window and a string is a wildcard not yet replaced.

get_delay

get_delay() -> float | str
Source code in unaiverse/hsm/action.py
def get_delay(self) -> float | str:
    """Returns the delay configured for this action (0 means no delay)."""
    return self.__delay

Returns delay in seconds. A value of 0 means no delay and a string is a wildcard not yet replaced. A delay that is still a string when the machine evaluates the transition raises TypeError.

is_pedantic

is_pedantic() -> bool
Source code in unaiverse/hsm/action.py
def is_pedantic(self) -> bool:
    """Checks if a retry_timeout has been configured for the Custom.

    Returns:
        A boolean indicating if a retry_timeout is set.
    """
    return self.__action_retry_timeout > 0

Returns True when retry_timeout is greater than 0. A pedantic action that fails returns code 1 and the machine keeps trying the same transition until the action succeeds or its retry window ends.

is_pedantic_by_default

is_pedantic_by_default() -> bool
Source code in unaiverse/hsm/action.py
def is_pedantic_by_default(self) -> bool:
    """Checks if an action was pedantic at construction time.

    Returns:
        A boolean indicating if the action was pedantic since when it was generated.
    """
    return self.__action_pedantic_by_default

Returns whether the action was pedantic when it was built (or when its retry_timeout wildcard was replaced). send(wait_completion=True) and stepwise() read it to restore the original behavior after they made the action pedantic for a while.

set_timeout

set_timeout(retry_timeout: float) -> None
Source code in unaiverse/hsm/action.py
def set_timeout(self, retry_timeout: float) -> None:
    """Sets the retry_timeout to a custom value."""
    self.__action_retry_timeout = retry_timeout
    if retry_timeout > 0.:
        self.__action_pedantic_by_default = False

Replaces the retry window of the action with the argument retry_timeout. A positive value also marks the action as not pedantic by default. send() and stepwise() call it with a positive value to make the action wait and with -1. to clear the window again. Returns None.

set_default_timeout

set_default_timeout() -> None
Source code in unaiverse/hsm/action.py
def set_default_timeout(self) -> None:
    """Sets the retry_timeout to the class-level default value (``Custom.DEFAULT_TIMEOUT``)."""
    if not self.is_pedantic():
        self.__action_retry_timeout = Custom.DEFAULT_TIMEOUT

Gives a non-pedantic action the retry window Custom.DEFAULT_TIMEOUT (10 seconds). A pedantic action keeps its own window. send(wait_completion=True) calls it and so does the binding of a multi-step interaction without a retry window to the action. Returns None.

Requests

add_interaction

add_interaction(interaction: Interaction) -> bool
Source code in unaiverse/hsm/action.py
def add_interaction(self, interaction: Interaction) -> bool:
    """Adds a new interaction to the action's internal list.
    This is used to track pending requests that might make the action ready to be executed.

    Args:
        interaction: Interaction object.
    """

    # Let's augment interaction object
    if not self.allows_outer_interactions():
        return False
    interaction.set_action_ref(self)
    self.interactions.add(interaction)
    return True

Appends interaction to the queue of pending requests and links it to this action. The link validates the arguments of the request and gives a multi-step interaction the default retry window when the action has none. Returns False without queuing when the action does not accept requests (outer is False) and True otherwise. A request whose arguments the action does not accept raises ValueError. HybridStateMachine.request_action() calls it.

get_list_of_interactions

get_list_of_interactions() -> ActionInteractionList
Source code in unaiverse/hsm/action.py
def get_list_of_interactions(self) -> 'ActionInteractionList':
    """Retrieves the list of pending interactions (ActionInteractionList object).

    Returns:
        The list of pending interactions, i.e., an object of type ActionInteractionList.
    """
    return self.interactions

Returns the ActionInteractionList of the pending requests. The object is not a copy.

clear_interactions

clear_interactions(requester: str | None = None) -> None
Source code in unaiverse/hsm/action.py
def clear_interactions(self, requester: str | None = None) -> None:
    """Clears all pending requests from the action's list."""
    if requester is None:
        self.interactions = ActionInteractionList()
    else:
        if self.interactions.is_requester_known(requester):
            requests = self.interactions.get_interactions(requester)
            assert isinstance(requests, list)
            for req in requests:
                self.interactions.remove(req)

Without arguments the method replaces the queue with an empty one. With requester it removes only the requests of that peer. Returns None.

clear_interaction

clear_interaction(requester: str, req_id: int) -> None
Source code in unaiverse/hsm/action.py
def clear_interaction(self, requester: str, req_id: int) -> None:
    """Removes a single specific interaction identified by requester and insertion-order ID.

    Args:
        requester: The peer ID of the requester who owns the interaction.
        req_id: The insertion-order ID of the interaction to remove.
    """
    req = self.interactions.get_interaction(req_id, requester)
    if req is not None:
        self.interactions.remove(req)

Removes the request at position req_id in the sub-list of requester. Nothing happens when that position is empty. Returns None.

same_as

same_as(name: str, args: dict | None) -> bool
Source code in unaiverse/hsm/action.py
def same_as(self, name: str, args: dict | None) -> bool:
    """Compares the current action to a target action by name and arguments. It returns `True` if they are
    considered the same, ignoring specific arguments like time or retry_timeout.

    Args:
        name: The name of the target Custom.
        args: The arguments of the target Custom.

    Returns:
        A boolean indicating if the actions are a match.
    """
    if args is None:
        args = {}

    # The current action is the same of another action called with some arguments "args" if:
    # 1) it has the same name of the other action
    # 2) the name of the arguments in "args" are known and valid
    # 3) the values of the arguments in "args" matches the ones of the current action, being them default or not
    # the values of those arguments that are not in "args" are assumed to the equivalent to the ones in the current
    # action, so:
    # - if the current action is act(a=3, b=4), then it is the same_as(name='act', args={'a': 3})
    # - if the current action is act(a=3, b=4), then it is the same_as(name='act', args={'a': 3, 'b': 4, 'c': 5})
    args_to_exclude = Custom.RESERVED_IN_ACTION_KWARGS
    return (name == self.name and
            self.check_provided_args(args) and
            all(k in args_to_exclude or k not in self.args or self.args[k] == v for k, v in args.items()))

Returns True when a call of name with args matches this action. Three conditions must hold: (1) name equals the name of the action, (2) check_provided_args(args) accepts the keys and (3) every key of args that the action also fixes has the same value. The keys max_duration, retry_timeout, delay, action_kwargs and interaction are not compared. Keys absent from args are not compared either. For an action act(a=3, b=4) the calls same_as("act", {"a": 3}) and same_as("act", {}) return True and same_as("act", {"a": 5}) returns False. The machine uses it to route requests and to refuse duplicated transitions.

check_provided_args

check_provided_args(args: dict, exception: bool = False, remove_special_arguments: bool = False) -> bool
Source code in unaiverse/hsm/action.py
def check_provided_args(self, args: dict, exception: bool = False, remove_special_arguments: bool = False) -> bool:
    """A helper method that validates that all provided arguments for an action exist in the action's
    parameter list. It can either raise a `ValueError` or return a boolean.

    Args:
        args: The dictionary of arguments to check.
        exception: If `True`, a `ValueError` is raised on failure.
        remove_special_arguments: If `True`, removes from the args dictionary those special arguments that are
            internally handled in a specific manner (such as time-related arguments).

    Returns:
        True if all arguments are valid, False otherwise (if `exception` is `False`).
    """
    if args is not None:
        for k in list(args.keys()):
            if k in Custom.HSM_TRANSIT_META_NAMES:
                if remove_special_arguments:
                    del args[k]
                elif exception:
                    raise ValueError(f"Parameter {k} is not a valid param for action"
                                     f" {self.name} (it is a private HSM transit meta name)")
                else:
                    return False
            elif k in Custom.WIRE_SENTINEL_NAMES or k in Custom.INTERACTION_INJECT_NAMES:
                if exception:
                    raise ValueError(f"Parameter {k} is not a valid param for action"
                                     f" {self.name} (it is reserved)")
                else:
                    return False
            elif k in Custom.INTERACTION_FIELD_NAMES:
                continue  # Skipping
            elif k not in self.param_list:
                if exception:
                    raise ValueError(f"Parameter {k} is not a valid param for action"
                                     f" {self.name} (it is not part of the action signature)")
                else:
                    return False
    return True

Validates the keys of args against the action and returns True when they are all acceptable. The method skips the interaction fields and refuses (1) the timing keys max_duration, retry_timeout and delay, (2) the reserved names action_kwargs and interaction and (3) any name outside the signature of the method. With remove_special_arguments=True the timing keys are deleted from args in place instead of being refused. With exception=True a refused key raises ValueError and with exception=False the method returns False.

get_actual_params

get_actual_params(additional_args: dict | None) -> dict | None
Source code in unaiverse/hsm/action.py
def get_actual_params(self, additional_args: dict | None) -> dict | None:
    """A helper method that resolves all parameters for an action's execution. It combines the action's
    default arguments, initial arguments, and any additional arguments provided during the call, ensuring all
    necessary parameters have a value.

    Args:
        additional_args: A dictionary of arguments to be combined with the action's defaults.

    Returns:
        A dictionary of all resolved arguments, or `None` if a required parameter is missing.
    """
    actual_params = {}
    params = self.param_list
    defaults = self.param_to_default_value
    for param_name in params:
        if param_name in self.args:
            actual_params[param_name] = self.args[param_name]
        elif additional_args is not None and param_name in additional_args:
            actual_params[param_name] = additional_args[param_name]
        elif param_name in defaults:
            actual_params[param_name] = defaults[param_name]
        else:
            log.error(f"Getting actual params for {self.name}; missing param: {param_name}")
            return None
    return actual_params

Returns the keyword arguments of the next call as a dictionary with one entry per parameter of the method. Each value comes from the arguments of the action, then from additional_args, then from the default of the parameter. A parameter without a value in any of the three sources is logged as an error and makes the method return None.

Wildcards and messages

set_wildcards

set_wildcards(wildcards: dict[str, str | float | int | list[str]] | None) -> None
Source code in unaiverse/hsm/action.py
def set_wildcards(self, wildcards: dict[str, str | float | int | list[str]] | None) -> None:
    """Replaces wildcard values with new ones.

    Args:
        wildcards: A dictionary mapping wildcard placeholders to their concrete values.
    """
    self.wildcards = wildcards if wildcards is not None else {}

Replaces the dictionary of wildcards with wildcards (an empty one for None). Returns None.

apply_wildcards

apply_wildcards() -> None
Source code in unaiverse/hsm/action.py
def apply_wildcards(self) -> None:
    """Given the current wildcards, it applies the replacements they suggest to whatever uses them."""

    # Setting up the original wildcard-based arguments and messages
    if self.args_with_wildcards is None:
        self.args_with_wildcards = copy.deepcopy(self.args)  # Backup before applying wildcards (1st time only)
    else:
        self.args = copy.deepcopy(self.args_with_wildcards)  # Restore a backup before applying wildcards
    if self.msg_with_wildcards is not None:
        self.msg = self.msg_with_wildcards

    # Applying wildcard-suggested replacements to arguments
    self.__apply_wildcards_to_args(self.args)

    # Applying wildcard-suggested replacements to message and other stuff
    for wildcard_from, wildcard_to in self.wildcards.items():

        # ... to message
        if self.msg is not None:
            self.msg = self.msg.replace(wildcard_from, str(wildcard_to))

        # ... to the rest
        if (self.__action_max_duration_with_wildcard is not None and
                wildcard_from in self.__action_max_duration_with_wildcard):
            self.__action_max_duration = (
                float(self.__action_max_duration_with_wildcard.replace(wildcard_from, str(wildcard_to))))
        if (self.__action_retry_timeout_with_wildcard is not None and
                wildcard_from in self.__action_retry_timeout_with_wildcard):
            self.__action_retry_timeout = (
                float(self.__action_retry_timeout_with_wildcard.replace(wildcard_from, str(wildcard_to))))
            self.__action_pedantic_by_default = self.is_pedantic()
        if self.__delay_with_wildcard is not None and wildcard_from in self.__delay_with_wildcard:
            self.__delay = float(self.__delay_with_wildcard.replace(wildcard_from, str(wildcard_to)))

    # Now that wildcards have been resolved in self.args, rebuild the system_interaction so any
    # streams / num_steps / etc. reflect the concrete (post-wildcard) values.
    self.__build_system_interaction()

Rebuilds args and msg from the copies written in the behavior, replaces the wildcards in them and converts the timing fields that held a wildcard with float(). The rules are those of Wildcards. A replaced retry_timeout also updates the pedantic default. The method then rebuilds the system interaction from the resolved arguments. Returns None.

set_msg

set_msg(msg: str | None) -> None
Source code in unaiverse/hsm/action.py
def set_msg(self, msg: str | None) -> None:
    """Sets the message associated to this Custom."""

    if msg is not None:
        self.msg = html.unescape(msg)
        self.msg_with_wildcards = self.msg
    else:
        self.msg = None
        self.msg_with_wildcards = None

Replaces the message with msg after decoding its HTML entities. Both msg and msg_with_wildcards take the new value and None removes the message. Returns None.

reset_msg_printing

reset_msg_printing() -> None
Source code in unaiverse/hsm/action.py
def reset_msg_printing(self) -> None:
    """Lets the message of the action be printed again at its next attempt (the action completed, or the state
    machine left the state the action starts from)."""
    self.__msg_printed_for = None

Lets the message be printed again at the next attempt. The machine calls it when the action completes and when the machine leaves the source state. The message of a failing action is otherwise printed once per series of retries. Returns None.

set_state_machine

set_state_machine(hsm: HybridStateMachine) -> None
Source code in unaiverse/hsm/action.py
def set_state_machine(self, hsm: "HybridStateMachine") -> None:
    """Registers the parent state machine that owns this action."""
    self.state_machine = hsm
    self.set_wildcards(hsm.get_wildcards())

Links the action to the machine hsm and gives it the wildcards of hsm. Returns None.

get_name

get_name() -> str
Source code in unaiverse/hsm/action.py
def get_name(self) -> str:
    return self.name

Returns the name of the method.

set_mark

set_mark(mark: object) -> None
Source code in unaiverse/hsm/action.py
def set_mark(self, mark: object) -> None:
    """Store an arbitrary marker object on the action."""
    self.__mark = mark

Stores an arbitrary object on the action. HybridStateMachine.to_dict() uses the marker while it groups the teleports. Returns None.

get_mark

get_mark() -> object
Source code in unaiverse/hsm/action.py
def get_mark(self) -> object:
    """Return the marker object previously set by set_mark."""
    return self.__mark

Returns the object stored by set_mark() or None.

clear_mark

clear_mark() -> None
Source code in unaiverse/hsm/action.py
def clear_mark(self) -> None:
    """Clear the arbitrary marker object on the action."""
    self.__mark = None

Removes the stored object. Returns None.

Serialization

to_dict

to_dict() -> dict
Source code in unaiverse/hsm/action.py
def to_dict(self) -> dict:
    """Converts the action's properties into a dict for easy serialization.

    Returns:
        A dict containing the action's properties.
    """
    return {
        "action": self.name,
        "action_kwargs": self.args,
        "msg": self.msg.encode("ascii",
                               "xmlcharrefreplace").decode("ascii") if self.msg is not None else None,
        "ready": self.inner,
        "high_priority": self.is_high_priority,
        Custom.SECONDS_ARG_NAMES[0]: self.__action_max_duration,
        Custom.TIMEOUT_ARG_NAMES[0]: self.__action_retry_timeout,
        Custom.DELAY_ARG_NAMES[0]: self.__delay
    }

Returns the field on of the JSON format: action, action_kwargs, msg (ASCII with HTML entities), ready, high_priority, max_duration, retry_timeout and delay. The arguments and the timing values are those after the replacement of the wildcards.

to_list

to_list() -> list
Source code in unaiverse/hsm/action.py
def to_list(self) -> list:
    """Converts the action's properties into a list for easy serialization and comparisons.

    Returns:
        A list containing the action's properties.
    """
    total_time = 0.
    retry_timeout = 0.
    delay = 0.
    if isinstance(self.__action_max_duration, str) or self.__action_max_duration > 0:
        total_time = self.__action_max_duration
    if isinstance(self.__action_retry_timeout, str) or self.__action_retry_timeout > 0.:
        retry_timeout = self.__action_retry_timeout
    if isinstance(self.__delay, str) or self.__delay > 0.:
        delay = self.__delay
    return [self.name, self.args, self.inner, self.outer, total_time, retry_timeout, delay, self.msg]

Returns [name, args, inner, outer, max_duration, retry_timeout, delay, msg] with the timing values clamped to 0. when they are not positive. HybridStateMachine.to_dict() compares these lists to find identical teleports.

to_code_str

to_code_str() -> str
Source code in unaiverse/hsm/action.py
def to_code_str(self) -> str:
    """Returns a compact code-style string representation of the action (for logging/debugging)."""
    s = f"aai:{self.name}|{self.args}|"
    if len(self.interactions) > 0:
        return s + "\n" + "\n".join(f"   {inter.to_code_str(True)}" for inter in self.interactions)
    else:
        return s + "no-int"

Returns a compact string for the logs of the form aai:name|args| followed by one line per pending interaction or by no-int when there is none.

ActionInteractionList

ActionInteractionList(max_per_requester: int = -1)
Source code in unaiverse/hsm/action.py
def __init__(self, max_per_requester: int = -1):
    """Initializes an empty interaction list with an optional per-requester cap.

    Args:
        max_per_requester: Maximum number of interactions stored per requester (-1 for unlimited).
    """
    self.by_insertion_order = []
    self.by_requester_and_by_insertion_order = {}
    self.max_per_requester = max_per_requester
    self.by_insertion_order_entering_time = []

The queue of the pending requests of one action. It keeps the interactions in a global insertion order and in a separate insertion order for each requester. Each interaction stores its positions in the two orders (by_insertion_order_id and by_requester_insertion_order_id) and -1 once it leaves the queue. The object supports len() and iteration in global insertion order.

Argument Type Default Meaning
max_per_requester int -1 The maximum number of interactions per requester. A new interaction beyond the limit evicts the oldest one of the same requester. A value of 0 or less means no limit.
Attribute Type Meaning
by_insertion_order list[Interaction] The interactions in global insertion order.
by_requester_and_by_insertion_order dict[str, list[Interaction]] The interactions of each requester in insertion order.
by_insertion_order_entering_time list[float] The time.perf_counter() value at which each interaction entered the queue.
max_per_requester int The constructor argument.

add

add(interaction: Interaction) -> None
Source code in unaiverse/hsm/action.py
def add(self, interaction: Interaction) -> None:
    """Appends an interaction to the list, updating all internal indices. Interactions with ``uuid=None`` are
    deduplicated per requester. If ``max_per_requester`` is set, the oldest entry for that requester is evicted.

    Args:
        interaction: The Interaction object to add.
    """

    # Searching for already existing interactions with this UUID, FROM THE SAME REQUESTER
    # If already there - do not accumulate multiple requests with same UUID (useful also for system interactions)
    assert interaction.requester is not None
    existing_request_same_uuid = self.get_interaction_by_uuid(interaction.requester, interaction.uuid)
    if existing_request_same_uuid:

        # We skip this request if we are already taking care (running) of another one with the same UUID
        if existing_request_same_uuid.running:  # This means the HSM is taking care of it, don't mess up things!
            log.error(f"Tried to add an interaction with the UUID of an already existing one that was in "
                      f"'running' state, skipping (requester: {interaction.requester}")
            return

        # Since we know the requester is the same, we just "refresh" the existing interaction object,
        # without altering its position in the list
        self.by_insertion_order[existing_request_same_uuid.by_insertion_order_id] = interaction
        interaction.by_insertion_order_id = existing_request_same_uuid.by_insertion_order_id

        self.by_requester_and_by_insertion_order[
            interaction.requester][existing_request_same_uuid.by_requester_insertion_order_id] = (
            interaction)
        interaction.by_requester_insertion_order_id = existing_request_same_uuid.by_requester_insertion_order_id
        return  # We stop here in this case, no need to do any other things

    # Updating by-requester index
    if interaction.requester not in self.by_requester_and_by_insertion_order:
        self.by_requester_and_by_insertion_order[interaction.requester] = []

    if 0 < self.max_per_requester <= len(self.by_requester_and_by_insertion_order[interaction.requester]):
        inter = self.get_oldest_interaction(interaction.requester)
        if inter is not None:
            self.remove(inter)
        else:
            log.critical("Unexpected behavior: getting the oldest interaction of a known requester returned None")
    by_requester_insertion_order_id = len(self.by_requester_and_by_insertion_order[interaction.requester])
    self.by_requester_and_by_insertion_order[interaction.requester].append(interaction)

    # Updating direct global index
    insertion_order_id = len(self.by_insertion_order)
    self.by_insertion_order.append(interaction)

    # Updating reverse indices
    interaction.by_insertion_order_id = insertion_order_id
    interaction.by_requester_insertion_order_id = by_requester_insertion_order_id

    # Saving joining time
    self.by_insertion_order_entering_time.append(time.perf_counter())

Appends interaction to the queue. An interaction with the same requester and the same uuid as a queued one replaces it in the same position. When the queued one is already running, the new one is logged as an error and dropped. The requester of the interaction must not be None (AssertionError). Returns None.

remove

remove(interaction: Interaction) -> None
Source code in unaiverse/hsm/action.py
def remove(self, interaction: Interaction) -> None:
    """Removes an interaction from the list, reindexing all subsequent entries to keep indices consistent.

    Args:
        interaction: The Interaction object to remove.
    """
    if interaction.is_valid():
        if (interaction.by_insertion_order_id < len(self.by_insertion_order) and
                self.by_insertion_order[interaction.by_insertion_order_id] == interaction):

            for i in range(interaction.by_insertion_order_id + 1, len(self.by_insertion_order)):
                self.by_insertion_order[i].by_insertion_order_id -= 1
            del self.by_insertion_order[interaction.by_insertion_order_id]
            del self.by_insertion_order_entering_time[interaction.by_insertion_order_id]

            d = self.by_requester_and_by_insertion_order[interaction.requester]
            for i in range(interaction.by_requester_insertion_order_id + 1, len(d)):
                d[i].by_requester_insertion_order_id -= 1
            del d[interaction.by_requester_insertion_order_id]
            if len(d) == 0:
                del self.by_requester_and_by_insertion_order[interaction.requester]
            interaction.by_insertion_order_id = -1
            interaction.by_requester_insertion_order_id = -1

Removes interaction from both orders, shifts the positions of the interactions after it and marks its positions as -1. An interaction that is not in the queue is ignored. Returns None.

remove_due_to_timeout

remove_due_to_timeout(timeout_secs: float) -> None
Source code in unaiverse/hsm/action.py
def remove_due_to_timeout(self, timeout_secs: float) -> None:
    """Removes all interactions that have been waiting longer than the specified retry_timeout.

    Args:
        timeout_secs: The maximum age in seconds; older interactions are removed.
    """
    to_remove = []
    for i, req in enumerate(self.by_insertion_order):
        if (time.perf_counter() - self.by_insertion_order_entering_time[i]) >= timeout_secs:
            to_remove.append(req)
    for req in to_remove:
        self.remove(req)

Removes every interaction that entered the queue at least timeout_secs seconds ago. Returns None.

remove_completed

remove_completed() -> None
Source code in unaiverse/hsm/action.py
def remove_completed(self) -> None:
    """Removes all interactions that have been marked as completed."""
    to_remove = []
    for i, req in enumerate(self.by_insertion_order):
        if req.completed:
            to_remove.append(req)
    for req in to_remove:
        self.remove(req)

Removes every interaction whose completed flag is True. Returns None.

move_interaction_to_back

move_interaction_to_back(interaction: Interaction) -> None
Source code in unaiverse/hsm/action.py
def move_interaction_to_back(self, interaction: Interaction) -> None:
    """Moves an interaction to the back of the insertion-order list, preserving its original entering time.

    Args:
        interaction: The Interaction object to reposition.
    """
    if len(self.by_insertion_order) > 1 and interaction.is_valid():
        try:
            entering_time = self.by_insertion_order_entering_time[interaction.by_insertion_order_id]
            self.remove(interaction)
            self.add(interaction)
            self.by_insertion_order_entering_time[interaction.by_insertion_order_id] = entering_time
        except Exception as e:
            raise e

Moves interaction to the end of both orders and keeps its original entering time. The machine calls it after a discarded attempt (code 2) to avoid serving the same request forever. Returns None.

move_requester_to_back

move_requester_to_back(requester: str) -> None
Source code in unaiverse/hsm/action.py
def move_requester_to_back(self, requester: str) -> None:
    """Moves all interactions belonging to a requester to the back of the list, preserving their entering times.

    Args:
        requester: The peer ID whose interactions should be moved to the back.
    """
    requests = self.get_interactions(requester)
    if requests is not None and isinstance(requests, list) and len(requests) > 0:
        requests_copy = []
        entering_times = []
        for req in requests:
            if req.is_valid():
                requests_copy.append(req)
                entering_times.append(self.by_insertion_order_entering_time[req.by_insertion_order_id])
                self.remove(req)
        for i, req in enumerate(requests_copy):
            self.add(req)
            self.by_insertion_order_entering_time[req.by_insertion_order_id] = entering_times[i]

Moves every interaction of requester to the end of the global order and keeps their entering times. Returns None.

get_interaction

get_interaction(req_order_id: int, requester: str | None = None) -> Interaction | None
Source code in unaiverse/hsm/action.py
def get_interaction(self, req_order_id: int, requester: str | None = None) -> Interaction | None:
    """Retrieves an interaction by its insertion-order index, optionally scoped to a specific requester.

    Args:
        req_order_id: The insertion-order index of the interaction to retrieve.
        requester: If provided, scopes the lookup to the sub-list of this requester.

    Returns:
        The matching Interaction, or None if not found.
    """
    if req_order_id < 0 and req_order_id != -1:
        return None
    if requester is None:
        return self.by_insertion_order[req_order_id] if req_order_id < len(self.by_insertion_order) else None
    else:
        if requester not in self.by_requester_and_by_insertion_order:
            return None
        return self.by_requester_and_by_insertion_order[requester][req_order_id] \
            if req_order_id < len(self.by_requester_and_by_insertion_order[requester]) else None

Returns the interaction at position req_order_id in the global order (in the order of requester when given). The position -1 means the last one and any other negative position returns None. A position past the end returns None. The position -1 on an empty queue raises IndexError.

get_oldest_interaction

get_oldest_interaction(requester: str | None = None, ignore_completed: bool = False) -> Interaction | None
Source code in unaiverse/hsm/action.py
def get_oldest_interaction(self, requester: str | None = None, ignore_completed: bool = False) \
        -> Interaction | None:
    """Returns the oldest (first-added) interaction, optionally scoped to a specific requester.

    Args:
        requester: If provided, scopes the lookup to the sub-list of this requester.
        ignore_completed: If True, completed interactions will be ignored/skipped.

    Returns:
        The oldest Interaction, or None if the list is empty.
    """
    if not ignore_completed:
        return self.get_interaction(0, requester)
    else:
        req = self.get_interaction(0, requester)
        i = 1
        if req is not None:
            while req.completed:
                if i < len(self):
                    req = self.get_interaction(i, requester)
                    i += 1
                else:
                    return None
        return req

Returns the first interaction of the global order (or of requester) and None for an empty queue. With ignore_completed=True the method skips completed interactions and returns None when all are completed. With both requester and ignore_completed=True the scan uses the length of the whole queue as its bound and can raise AttributeError when the requester has fewer interactions.

get_most_recent_interaction

get_most_recent_interaction(requester: str | None = None, ignore_completed: bool = False) -> Interaction | None
Source code in unaiverse/hsm/action.py
def get_most_recent_interaction(self, requester: str | None = None, ignore_completed: bool = False) \
        -> Interaction | None:
    """Returns the most recently added interaction, optionally scoped to a specific requester.

    Args:
        requester: If provided, scopes the lookup to the sub-list of this requester.
        ignore_completed: If True, completed interactions will be ignored/skipped.

    Returns:
        The most recent Interaction, or None if the list is empty.
    """
    if not ignore_completed:
        return self.get_interaction(-1, requester)
    else:
        req = self.get_interaction(-1, requester)
        i = len(self) - 2
        if req is not None:
            while req.completed:
                if i >= 0:
                    req = self.get_interaction(i, requester)
                    i -= 1
                else:
                    return None
        return req

Returns the last interaction of the global order (or of requester). With ignore_completed=True the method scans backwards past completed interactions. An empty queue raises IndexError because the lookup uses the position -1.

get_interaction_by_uuid

get_interaction_by_uuid(requester: str, uuid: str | None) -> Interaction | None
Source code in unaiverse/hsm/action.py
def get_interaction_by_uuid(self, requester: str, uuid: str | None) -> Interaction | None:
    """Finds the first interaction for a given requester that matches the specified UUID.

    Args:
        requester: The peer ID of the requester.
        uuid: The UUID to search for (None is a valid UUID).

    Returns:
        The matching Interaction, or None if not found.
    """
    requests = self.get_interactions(requester)
    if requests is None or len(requests) == 0:
        return None

    assert isinstance(requests, list)
    for req in requests:
        if req.uuid == uuid:
            return req
    return None

Returns the first interaction of requester whose uuid equals uuid (None is a valid uuid) or None when there is no match.

keep_only_the_most_recent_interaction

keep_only_the_most_recent_interaction(ignore_completed: bool = False) -> None
Source code in unaiverse/hsm/action.py
def keep_only_the_most_recent_interaction(self, ignore_completed: bool = False) -> None:
    """Discards all interactions except the most recently added one, preserving its entering time.

    Args:
        ignore_completed: If True, completed interactions will be ignored/skipped.

    Returns:
        None
    """
    req = self.get_most_recent_interaction(ignore_completed=ignore_completed)
    if req is not None:
        entering_time = self.by_insertion_order_entering_time[req.by_insertion_order_id]
        self.clear()
        self.add(req)
        self.by_insertion_order_entering_time[req.by_insertion_order_id] = entering_time
    else:
        self.clear()

Empties the queue except for the most recent interaction (the most recent one not completed with ignore_completed=True) and keeps the entering time of that interaction. An empty queue raises IndexError. Returns None.

get_interactions

get_interactions(requester: str | None = None, to_str: bool = False, doable_only: bool = False) -> list[Interaction] | str
Source code in unaiverse/hsm/action.py
def get_interactions(self, requester: str | None = None, to_str: bool = False,
                     doable_only: bool = False) -> list[Interaction] | str:
    """Returns interactions, optionally filtered by requester or "do-ability", or as a JSON string.

    Args:
        requester: If provided, returns only interactions from this requester.
        to_str: If True, returns a JSON-encoded string instead of a list.
        doable_only: If True, filters to only interactions that pass ``check_if_doable()``.

    Returns:
        A list of Interaction objects, or a JSON-encoded string if ``to_str`` is True.
    """
    if requester is None:
        reqs = self.by_insertion_order
        if doable_only:
            reqs = [req for req in reqs if req.check_if_doable()]  # This excludes completed too
        if not to_str:
            return reqs
        else:
            return json.dumps([req.to_str() for req in reqs])
    else:
        if requester in self.by_requester_and_by_insertion_order:
            reqs = self.by_requester_and_by_insertion_order[requester]
            if doable_only:
                reqs = [req for req in reqs if req.check_if_doable()]
            if not to_str:
                return reqs
            else:
                return json.dumps([req.to_str() for req in reqs])
        else:
            if not to_str:
                return []
            else:
                return json.dumps([])

Returns the list of the queued interactions, all of them or those of requester alone. Without any filter the method returns the internal list and not a copy. doable_only=True keeps the interactions that can be served now (not completed, known requester, fresh data on every stream). to_str=True returns a JSON string with the to_str() of each interaction instead of the list. An unknown requester gives an empty list.

clear

clear() -> None
Source code in unaiverse/hsm/action.py
def clear(self) -> None:
    """Removes all interactions and resets all internal indices."""
    self.by_insertion_order.clear()
    self.by_requester_and_by_insertion_order.clear()
    self.by_insertion_order_entering_time.clear()

Empties the queue and its indices. The positions stored in the removed interactions are not reset. Returns None.

is_requester_known

is_requester_known(requester: str) -> bool
Source code in unaiverse/hsm/action.py
def is_requester_known(self, requester: str) -> bool:
    """Checks whether any interactions from the given requester are currently stored.

    Args:
        requester: The peer ID to look up.

    Returns:
        True if the requester has at least one interaction in the list, False otherwise.
    """
    return requester in self.by_requester_and_by_insertion_order

Returns True when the queue holds at least one interaction of requester.