Skip to content

unaiverse.hsm.hsm

This module holds HybridStateMachine, the class of every behavior in UNaIVERSE. A behavior is a state machine whose transitions are labeled by actions, the @action methods of an agent that the machine calls by name. At each clock cycle the node calls act() on the machine of the network where the agent is behaving. The machine runs the action of the current state, collects the transitions whose action can run now, asks a policy to pick one of them and runs it. An action that returns True moves the machine to the destination state of its transition. The machine is called hybrid because an action is Python code with a duration of its own that can wait for data, last several cycles or serve the requests of other agents.

Every agent owns two machines. agent.behav_lone_wolf drives the agent on the public network and is loaded from unaiverse/utils/public.json when the agent is created. agent.behav drives the agent inside a world. It starts as a machine with the single state empty and keeps that form until a world sends the behavior of a role. A world reads one JSON file per role from its folder (see unaiverse.world). Three classes take part in the machine: (1) HybridStateMachine holds the graph and runs it, (2) State is a node of the graph with an optional action of its own and (3) Action wraps one method of the agent with its arguments, its timing and its queue of requests.

from unaiverse.agent import Agent, action
from unaiverse.hsm import HybridStateMachine

class Sensor(Agent):

    @action
    async def calibrate(self, offset: float = 0.0) -> bool:
        self.offset = offset
        return True

    @action
    async def measure(self, interaction=None) -> bool:
        return await self.process(interaction=interaction)

sensor = Sensor(proc=None)
hsm = HybridStateMachine(sensor)
hsm.add_state("idle", blocking=True, msg="Waiting for requests")
hsm.add_transit("idle", "calibrated", action="calibrate", args={"offset": 0.5})
hsm.add_transit("calibrated", "idle", action="measure", timeout=5.)
hsm.set_role("sensor")
hsm.save("sensor.json")

Because measure declares a parameter named interaction, the machine runs it only when another agent requests it (see the argument avoid_changing_ready of add_transit). The file written by save() has the format of the next section and loads back with HybridStateMachine(sensor).load("sensor.json").

The JSON format

A behavior file is a JSON object with the four keys machine, states, transitions and teleports. load() reads it and save() writes it in the complete form shown below.

{
  "machine": {
    "role": "student",
    "initial_state": "waiting",
    "msg": "Welcome to the class",
    "options": {
      "highlight_blocking_states_in_messages": false,
      "show_action_ticks_after_messages": false,
      "show_action_request_after_messages": false
    }
  },
  "states": {
    "waiting": {"action": null, "action_kwargs": {}, "msg": null, "blocking": true,
                "time_to_wait_before_acting": 0.0},
    "studying": {"action": "read_notes", "action_kwargs": {"chapter": 3}, "msg": "Studying",
                 "blocking": false, "time_to_wait_before_acting": 2.0}
  },
  "transitions": {
    "waiting": [
      {"on": {"action": "learn", "action_kwargs": {}, "msg": "Learning", "ready": false,
              "high_priority": false, "max_duration": 0.0, "retry_timeout": 0.0, "delay": 0.0},
       "goto": "studying"}
    ],
    "studying": [
      {"on": {"action": "nop", "action_kwargs": {}, "msg": null, "ready": true,
              "high_priority": false, "max_duration": 0.0, "retry_timeout": 0.0, "delay": 1.5},
       "goto": "waiting"}
    ]
  },
  "teleports": {
    "all": [
      {"on": {"action": "disengage", "action_kwargs": {}, "msg": null, "ready": false,
              "high_priority": true, "max_duration": 0.0, "retry_timeout": 0.0, "delay": 0.0},
       "goto": "waiting"}
    ]
  }
}

A file without the key machine is read as the old list-based format by load_backward_compat.

machine

Field Required Default Meaning
role yes none The role implemented by the machine. load() passes it to set_role() and this method also writes it into the wildcard <role>. The public behavior uses "public".
initial_state yes none The state where the machine starts and where reset_state() brings it back. With null the first state added to a new machine becomes the initial one.
msg no null The welcome message that act() prints once through the user log channel when the machine is in its initial state.
options yes none An object with three booleans that default to false when absent. highlight_blocking_states_in_messages appends a red or green mark to the message of a blocking or non-blocking state. show_action_ticks_after_messages logs a tick with the outcome after the message of an action. show_action_request_after_messages appends the requester and the interaction uuid to the message of an action.

A missing role, initial_state or options makes load() raise GenException with the text Invalid JSON data format when loading the state machine. A missing states raises the same exception.

states

An object from the state name to its definition. The name all is reserved for the transitions that leave every state and a state with that name raises GenException.

Field Default Meaning
action null The name of an action that runs in the state at every pass of act() before the machine looks at the transitions. Its return value is ignored.
action_kwargs {} The arguments of that action. The values may contain wildcards.
msg null A message printed once through the user log channel when the machine enters the state.
blocking true With true the current call of act() ends as soon as the machine enters the state and the transitions of the new state wait for the next cycle. With false the call of act() continues with the new state in the same cycle.
time_to_wait_before_acting 0.0 Seconds after entering the state during which the machine considers only the transitions whose action has a pending request. Actions on the initiative of the agent wait until this time has passed.

An action that runs inside a state is always ready. The machine creates it with ready=True and keeps that flag even when the method declares a parameter named interaction.

transitions

An object from the source state to a list of transitions. Each transition is an object with two keys: on describes the action and goto names the destination state. A state named only in transitions and absent from states is created with the defaults of the previous table.

Field of on Default Meaning
action required The name of the method of the agent run by the transition. A missing key raises KeyError and a name missing from the agent raises AttributeError.
action_kwargs {} The arguments passed to the method. A key that is neither a parameter of the method nor one of the interaction fields of Custom.INTERACTION_FIELD_NAMES raises ValueError. The values may contain wildcards.
msg null A message printed through the user log channel at the first attempt of the action.
ready true With true the machine may run the action on the initiative of the agent. With false the action is request-only and runs only when another agent asks for it. When the key is absent and the method declares a parameter named interaction, the action becomes request-only. A key present in the file keeps its value as written.
high_priority false The default policy picks the first high-priority action among the feasible ones before looking at requests and at ready actions.
max_duration 0.0 The maximum life of the action in seconds since its first attempt. Past it the attempt is closed. A value of 0 or less means no limit.
retry_timeout 0.0 The seconds since the last successful step during which the machine keeps retrying the action after a failure. A value greater than 0 makes the action pedantic: a failure keeps the machine on this action instead of moving to the next candidate. With 0 or less a failure discards the attempt at once.
delay 0.0 Seconds that must pass after the machine entered the source state before this transition becomes feasible.

The three timing fields also accept a wildcard string such as "<exam_time>" and the machine converts it to a number when it applies the wildcards (see Wildcards). The timing fields can also appear inside action_kwargs. In that place they override the values of on and the machine removes them from the arguments before the call.

The source state all adds the transition to every state that exists when the entry is read and differs from the destination. Under transitions each of these copies is an ordinary transition and not a teleport. The candidates of a state are ordered first by destination (in the order in which each destination first appeared) and then by the order of the file. The default policy depends on this order.

teleports

This section has the same shape as transitions. A teleport is an ordinary transition that the drawing shows in a faded color (#00000050) and that to_dict() writes under teleports. Because load() reads the teleports after all the ordinary transitions, a teleport comes after the transitions of the same pair of states in the candidate order. Among the teleports the key all is expanded before the other source states. It covers every state known once the transitions are read except the destination. When to_dict() finds the same teleport from every state other than its destination, it writes one entry under all.

Wildcards

A wildcard is a string (usually of the form <name>) replaced by the machine in the arguments, in the timing fields and in the messages of its actions and states. The dictionary wildcards maps each wildcard to its value. Every machine starts with four wildcards mapped to themselves (see Custom.DEFAULT_WILDCARDS) and the node fills them later.

Wildcard Filled by Value
<agent> the node, at start and when it joins a world The peer id of the agent on the network of the machine.
<world> the node, when it joins a world The peer id of the world.
<role> set_role() The role of the machine.
<partner> the node and the agent, in the public machine The public peer that got in touch last.

apply_wildcards() rebuilds every argument from the copy written in the behavior and replaces the wildcards in it. A wildcard whose value is a string replaces each of its occurrences inside a string argument: "<world>:all" becomes "12D3Koo...:all". A wildcard whose value has another type (a number, a list) replaces an argument only when the whole argument equals the wildcard: with {"<eval_steps>": 30} the argument "num_steps": "<eval_steps>" becomes the integer 30. The replacement walks nested dictionaries and lists. Timing fields that hold a wildcard go through float() after the replacement. A world gives its members extra wildcards with agent.add_behav_wildcard(wildcard_from, wildcard_to) and the node adds them to agent.behav when the agent joins.

One call of act()

  1. When the machine is in its initial state and has a welcome message, the message is printed and then removed from the machine.
  2. act_states() runs the action of the current state when the state has one.
  3. act_transitions(only_the_ones_with_interactions=must_wait()) collects the feasible actions of the transitions that leave the current state. An action is feasible when its delay has passed since the machine entered the state and when it is ready or has at least one pending request that can be served now. During the time_to_wait_before_acting of the state only the actions with such a request are collected.
  4. The policy picks one action and optionally one of its pending interactions. The policy filter can change or veto the choice.
  5. While the action runs, state is None and limbo_state holds the source state. The action returns one of the codes of the next table.
  6. Steps 1 to 5 repeat as long as the action completes and the new state is not blocking. It stops in three cases: (1) the machine entered a blocking state, (2) the action returned code 1 and (3) no candidate completed.
Code of the action Meaning What the machine does
0 Completed. It moves to the destination state, completes the interaction with reason OK and returns 0 from act_transitions().
1 Run again. It stays on the same action and resumes it at the next call of act_transitions() without asking the policy. Other transitions are not tried meanwhile.
2 Discarded. It returns to the source state, moves the served interaction to the back of the queue of the action and asks the policy again over the remaining candidates. The action leaves the candidate list of this cycle once each of its pending interactions had a turn.
-1 Unexpected. act_transitions() raises ValueError("Unexpected status: -1"). An interaction whose num_steps is 0 produces this code.

Action explains how the value True or False returned by the method becomes one of these codes. A non-blocking state that loops on itself with an action that always completes makes act() loop without end inside one cycle.

Policies

A policy is a callable policy(actions_list) -> (index, interaction). actions_list is the list of feasible Action objects in candidate order. The policy returns the index of the chosen action together with the Interaction to serve. An interaction equal to None runs the action on the system interaction of the agent itself. Returning (-1, None) chooses nothing and ends act_transitions() with -1.

The default policy checks three rules in order: (1) the first high-priority action with its oldest pending interaction (or None), (2) the first action with at least one pending interaction together with the oldest one and (3) the first action that is ready on its own. An agent installs the equivalent method policy_default and replaces it with await agent.set_policy(policy, public=False).

A policy filter is a callable filter(index, interaction, actions_list, opts) -> (index, interaction) that receives the decision of the policy. When the filter raises an exception, the machine logs it and keeps the decision of the policy. A returned index of -1 vetoes the chosen action: the machine treats it as discarded (code 2) and asks the policy again over the remaining candidates. An agent installs a filter with agent.set_policy_filter(filter_fcn, public=False) and this method also writes the keys agent and public into opts.

def prefer_requests_from_teacher(idx, interaction, actions_list, opts):
    agent = opts["agent"]
    teachers = set(agent.get_agents_by_role("teacher"))
    for i, act in enumerate(actions_list):
        for inter in act.get_list_of_interactions():
            if inter.requester in teachers:
                return i, inter
    return idx, interaction

HybridStateMachine

HybridStateMachine(agent: AgentBasics, wildcards: dict[str, str | float | int] | None = None, policy: Callable[[list[Action]], tuple[int, Interaction | None]] | None = None)
Source code in unaiverse/hsm/hsm.py
def __init__(self, agent: "AgentBasics", wildcards: dict[str, str | float | int] | None = None,
             policy: Callable[[list[Action]], tuple[int, Interaction | None]] | None = None):
    """Initializes a `HybridStateMachine` object, which orchestrates states and transitions. It manages a set of
    states and actions, and handles the logic for transitions between states based on conditions and a defined
    policy. It sets up initial and current states, wildcards for dynamic arguments, and references to an
    `agent` object whose methods are the actions to be called. It also includes debug and output settings.

    Args:
        agent: The object on which actions (methods) are to be executed.
        wildcards: A dictionary of key-value pairs for dynamic argument substitution.
        policy: An optional callable that determines which action to execute from a list of feasible actions.
    """

    # States are identified by strings, and then handled as State object with possibly and integer ID and action
    self.initial_state = None  # Initial state of the machine
    self.prev_state = None  # Previous state
    self.limbo_state = None  # When an action takes more than a step to complete, we are in "limbo"
    self.state: str | None = None  # Current state
    self.role: str | None = None  # Role of the agent in the state machine (e.g., teacher, student, etc.)
    self.enabled: bool = True
    self.states: dict[str, State] = {}  # State name to State object

    # Actions (transitions) are handled as Action objects in-between state strings
    self.transitions: dict[str, dict[str, list[Action]]] = {}  # Pair-of-states to the actions between them
    self.agent: "AgentBasics" = agent  # The object on whose methods are actions that the machine calls
    self.wildcards: dict[str, str | float | int | list[str]] = wildcards \
        if wildcards is not None else {}  # From a wildcards string to a specific value (used in action arguments)
    self.policy = policy if policy is not None else self.__policy_first_requested_or_first_ready
    self.policy_filter: Callable | None = None
    self.policy_filter_opts = {}
    self.welcome_msg = None
    self.welcome_msg_with_wildcards = None
    self.show_blocking_states = False
    self.show_action_completion = False
    self.show_action_request_info = False

    # Running data
    self.__action: Action | None = None  # Action that is being executed (could take more than a step to complete)
    self.__last_completed_action: Action | None = None
    self.__cur_feasible_actions_status: dict | None = None  # Store info of the executed action (for multi-steps)
    self.__id_to_state: list[State] = []  # Map from state ID to State object
    self.__id_to_action: list[Action] = []  # Map from action ID to Action object
    self.__state_changed = False  # Internal flag
    self.__id_to_original_state_msg: list[tuple[str | None, str | None]] = []
    self.__id_to_original_action_msg: list[str | None] = []

    # Forcing default wildcards
    self.add_wildcards(Custom.DEFAULT_WILDCARDS)

    # Applying to the welcome message, state, actions, if needed
    self.apply_wildcards()

    # Forcing output function
    self.__debug_messages_active = False

    self.set_actionable(agent)  # Propagating to inner actions

The state machine of one behavior. The agent creates its two machines by itself. A developer creates one directly in two cases: to build a behavior in code and save it (as a world does in create_behav_files) and to inspect a behavior file.

Argument Type Default Meaning
agent AgentBasics required The object whose methods are the actions. Every action name is resolved on it with getattr when the transition is added.
wildcards dict[str, str \| float \| int] \| None None The initial wildcards. The machine keeps this same dictionary object, adds the four default wildcards to it and modifies it in place later.
policy Callable \| None None The policy. None installs the default policy described above.
Attribute Type Meaning
states dict[str, State] The states by name.
transitions dict[str, dict[str, list[Action]]] The actions between each pair of states. transitions[from_state][to_state] is the list of actions from from_state to to_state with the teleports included.
state str \| None The current state. It is None while an action runs.
limbo_state str \| None The source state of the running action. It is None when no action runs.
prev_state str \| None The state before the last transition.
initial_state str \| None The initial state.
role str \| None The role given by set_role().
enabled bool With False the methods act_states() and act_transitions() do nothing.
agent AgentBasics The object that owns the actions.
wildcards dict The wildcards. Every state and action of the machine holds a reference to this same dictionary.
policy, policy_filter, policy_filter_opts The policy, the filter (None by default) and the options dictionary passed to the filter.
welcome_msg, welcome_msg_with_wildcards str \| None The welcome message after and before the replacement of the wildcards.
show_blocking_states, show_action_completion, show_action_request_info bool The three display options of machine.options.

Building a machine

add_state

add_state(state: str, action: str | None = None, args: dict | None = None, state_id: int | None = None, waiting_time: float | None = None, blocking: bool | None = None, msg: str | None = None, msg_action: str | None = None) -> None
Source code in unaiverse/hsm/hsm.py
def add_state(self, state: str, action: str | None = None, args: dict | None = None, state_id: int | None = None,
              waiting_time: float | None = None, blocking: bool | None = None,
              msg: str | None = None, msg_action: str | None = None) -> None:
    """Adds a new state to the state machine. This method can create a new state with an optional inner action or
    update an existing state. It assigns a unique ID to the state and its action.

    Args:
        state: The name of the state to add.
        action: The name of the action to associate with the state.
        args: A dictionary of arguments for the action.
        state_id: An optional unique ID for the state.
        waiting_time: A float representing a delay before the state can transition.
        blocking: A boolean indicating if the state is blocking.
        msg: A human-readable message for the state.
        msg_action: A human-readable message for the action running on this state.
    """
    if args is None:
        args = {}
    sta_obj = None
    if state_id is None:
        if state not in self.states:
            state_id = len(self.__id_to_state)
        else:
            sta_obj = self.states[state]
            state_id = sta_obj.id
    if action is None:
        act = sta_obj.action if sta_obj is not None else None
    else:
        assert self.agent is not None
        act = Action(name=action, args=args, idx=len(self.__id_to_action),
                     agent=self.agent, avoid_changing_ready=True,
                     msg=msg_action)
        act.set_wildcards(self.wildcards)
        self.__id_to_action.append(act)
    if waiting_time is None:
        waiting_time = sta_obj.waiting_time if sta_obj is not None else 0.  # Default waiting time
    if blocking is None:
        blocking = sta_obj.blocking if sta_obj is not None else True  # Default blocking
    if msg is None:
        msg = sta_obj.msg_with_wildcards if sta_obj is not None else None

    sta = State(name=state, idx=state_id, action=act, waiting_time=waiting_time, blocking=blocking, msg=msg)
    sta.set_wildcards(self.wildcards)
    if state not in self.states:
        self.__id_to_state.append(sta)
    else:
        self.__id_to_state[state_id] = sta
    self.states[state] = sta

    if len(self.__id_to_state) == 1 and self.state is None:
        self.set_state(sta.name)

    sta.set_state_machine(self)

Adds a state or replaces the definition of an existing one and returns None.

Argument Type Default Meaning
state str required The name of the state. The name "all" raises GenException.
action str \| None None The name of an action to run in the state. With None the state keeps the action it already had.
args dict \| None None The arguments of that action. They are ignored when action is None.
state_id int \| None None A numeric id. With None a new state gets the next free index and an existing one keeps its id. Only the old file format passes it.
waiting_time float \| None None The JSON field time_to_wait_before_acting in seconds. With None the state keeps the previous value (0.0 for a new state).
blocking bool \| None None The JSON field blocking. With None the state keeps the previous value (True for a new state).
msg str \| None None The JSON field msg of the state. With None the state keeps the previous message.
msg_action str \| None None The message of the action of the state. This message has no JSON field and save() does not write it.

A new definition replaces the State object and copies from the old one every field missing from the call. The first state added to a machine with no current state becomes both the current and the initial state. A new state action is always ready (see JSON states). The method raises AttributeError when the agent lacks the method and ValueError when args holds a name not accepted by the method.

hsm.add_state("exam", action="nop", args={"message": "Exam started"}, blocking=False, waiting_time=3.)
hsm.add_state("exam", blocking=True)  # keeps the action, the arguments and the waiting time

add_transit

add_transit(from_state: str, to_state: str, action: str, args: dict | None = None, ready: bool = True, act_id: int | None = None, msg: str | None = None, avoid_changing_ready: bool = False, teleport: bool = False, high_priority: bool = False, total_time: float | str = 0.0, timeout: float | str = 0.0, delay: float | str = 0.0) -> None
Source code in unaiverse/hsm/hsm.py
def add_transit(self, from_state: str, to_state: str,
                action: str, args: dict | None = None, ready: bool = True,
                act_id: int | None = None, msg: str | None = None,
                avoid_changing_ready: bool = False,
                teleport: bool = False,
                high_priority: bool = False,
                total_time: float | str = 0., timeout: float | str = 0., delay: float | str = 0.,) -> None:
    """Defines a transition between two states with an associated action. This method is central to building the
    state machine's logic. It can also handle loading and integrating a complete state machine from a file,
    resolving any state name clashes.

    Args:
        from_state: The name of the starting state.
        to_state: The name of the destination state (can be a file path to load another HSM).
        action: The name of the action to trigger the transition.
        args: A dictionary of arguments for the action.
        ready: A boolean indicating if the action is ready by default.
        act_id: An optional unique ID for the action.
        msg: An optional human-readable message for the action.
        avoid_changing_ready: A boolean indicating that the selected ready state should not be changed by
            internal rules.
        teleport: A boolean indicating that this transition must be hidden when drawing the machine ('teleport').
        high_priority: A boolean indicating that this transition must be preferred by the policy over others.
        total_time: The number of seconds representing the max duration of this transition (from when it stars).
            When <= 0., then no limits.
        timeout: The number of seconds representing the max time we keep try running this transition before
            giving up. When <= 0., then no timeouts at all.
        delay: The number of seconds that must pass when joining a state before considering this transition.
            When <= 0., then no delays at all.
    """

    # Handling special state names
    if from_state == Custom.ALL_STATES_NAME:
        for from_state_obj in self.__id_to_state:

            # Skipping the destination state, mirroring the load-time 'all' expansion
            if from_state_obj.name == to_state:
                continue

            # Adding a transition to the dest state
            self.add_transit(from_state=from_state_obj.name, to_state=to_state, action=action, args=args,
                             ready=ready, act_id=None, avoid_changing_ready=avoid_changing_ready,
                             msg=msg, teleport=teleport, high_priority=high_priority,
                             total_time=total_time, timeout=timeout, delay=delay)
        return

    # Plugging a previously loaded HSM
    if to_state.lower().endswith(".json"):
        if not os.path.exists(to_state):
            raise FileNotFoundError(f"Cannot find {to_state}")

        file_name = to_state
        hsm = HybridStateMachine(self.agent).load(file_name)

        # First, we avoid name clashes, renaming already-used-state-names in original_name~1 (or ~2, or ~3, ...)
        hsm_states = list(hsm.states.keys())  # Keep the list(...) thing, since we need a copy here (it will change)
        for state in hsm_states:
            renamed_state = state
            i = 1
            while renamed_state in self.states or (i > 1 and renamed_state in hsm.states):
                renamed_state = state + "." + str(i)
                i += 1

            if hsm.initial_state == state:
                hsm.initial_state = renamed_state
            if hsm.prev_state == state:
                hsm.prev_state = renamed_state
            if hsm.state == state:
                hsm.state = renamed_state
            if hsm.limbo_state == state:
                hsm.limbo_state = renamed_state

            hsm.states[renamed_state] = hsm.states[state]
            if renamed_state != state:
                del hsm.states[state]
            hsm.transitions[renamed_state] = hsm.transitions[state]
            if renamed_state != state:
                del hsm.transitions[state]

            for to_states in hsm.transitions.values():
                if state in to_states:
                    to_states[renamed_state] = to_states[state]
                    if renamed_state != state:
                        del to_states[state]

        # Saving
        initial_state_was_set = self.initial_state is not None
        state_was_set = self.state is not None

        # Include actions/states from another HSM
        self.include(hsm)

        # Adding a transition to the initial state of the given HSM
        self.add_transit(from_state=from_state, to_state=hsm.initial_state, action=action, args=args,
                         ready=ready, act_id=None, msg=msg, teleport=teleport, high_priority=high_priority,
                         total_time=total_time, timeout=timeout, delay=delay)

        # Restoring
        self.initial_state = from_state if not initial_state_was_set else self.initial_state
        self.state = from_state if not state_was_set else self.state
        return

    # Adding a new transition
    if from_state not in self.transitions:
        if from_state not in self.states:
            self.add_state(from_state, action=None)
        self.transitions[from_state] = {}
    if to_state not in self.transitions:
        if to_state not in self.states:
            self.add_state(to_state, action=None)
        self.transitions[to_state] = {}
    if args is None:
        args = {}
    if act_id is None:
        act_id = len(self.__id_to_action)

    # Clearing
    if to_state not in self.transitions[from_state]:
        self.transitions[from_state][to_state] = []

    # Checking
    existing_action_list = self.transitions[from_state][to_state]
    for existing_action in existing_action_list:
        if existing_action.same_as(name=action, args=args):
            raise ValueError(f"Repeated transition from {from_state} to {to_state}: "
                             f"{existing_action.to_list()}")

    # Adding the new action
    new_action = Action(name=action, args=args, idx=act_id, agent=self.agent, ready=ready, msg=msg,
                        avoid_changing_ready=avoid_changing_ready,
                        teleport=teleport, high_priority=high_priority,
                        max_duration=total_time, retry_timeout=timeout, delay=delay)
    self.transitions[from_state][to_state].append(new_action)
    self.__id_to_action.append(new_action)

    new_action.set_state_machine(self)  # This will also share the same wildcards dictionary

Adds a transition labeled by action from from_state to to_state and returns None. Missing states are created with the defaults of add_state(). The arguments map to the JSON fields as follows.

Argument JSON field Type Default Meaning
from_state key of transitions str required The source state. With "all" the transition is added to every current state other than to_state.
to_state goto str required The destination state or the path of another behavior file (see below).
action on.action str required The name of the method of the agent.
args on.action_kwargs dict \| None None The arguments of the method.
ready on.ready bool True Whether the action can run on the initiative of the agent.
act_id none int \| None None The numeric id of the action. With None the action gets the next free index.
msg on.msg str \| None None The message of the action.
avoid_changing_ready presence of on.ready bool False With True the flag ready stays as given. With False the action turns request-only when the method declares a parameter named interaction. load() passes True exactly when the file has the key ready.
teleport section teleports bool False Whether the transition is a teleport.
high_priority on.high_priority bool False Whether the default policy prefers it.
total_time on.max_duration float \| str 0. The maximum life of the action in seconds or a wildcard.
timeout on.retry_timeout float \| str 0. The retry window in seconds or a wildcard.
delay on.delay float \| str 0. The delay after entering from_state in seconds or a wildcard.

A to_state that ends with .json (in any case) plugs another behavior into this one. The method loads the file into a new machine with the same agent and renames each of its states that clashes with a state of this machine by appending .1, .2 and so on. It then merges the loaded machine with include() and adds the transition from from_state to the initial state of the loaded machine. When this machine had no initial or current state, from_state becomes both. A missing file raises FileNotFoundError.

The method raises ValueError in two cases: (1) the same pair of states already has an action equal to the new one according to Action.same_as and (2) an argument is not accepted by the method. It raises AttributeError when the agent lacks the method and GenException when the method declares a reserved parameter (max_duration, retry_timeout, delay, or action_kwargs outside send).

hsm.add_transit("ready", "evaluated", action="evaluate",
                args={"stream_hash": "<world>:exam", "how": "mse", "steps": "<eval_steps>"},
                total_time="<exam_time>", timeout=30.)
hsm.add_transit("evaluated", "templates/badge_flow.json", action="nop")

add_teleport

add_teleport(from_state: str, to_state: str, action: str, args: dict | None = None, ready: bool = True, act_id: int | None = None, msg: str | None = None, avoid_changing_ready: bool = False, high_priority: bool = False, total_time: float | str = 0.0, timeout: float | str = 0.0, delay: float | str = 0.0) -> None
Source code in unaiverse/hsm/hsm.py
def add_teleport(self, from_state: str, to_state: str,
                 action: str, args: dict | None = None, ready: bool = True,
                 act_id: int | None = None, msg: str | None = None, avoid_changing_ready: bool = False,
                 high_priority: bool = False,
                 total_time: float | str = 0., timeout: float | str = 0., delay: float | str = 0., ) -> None:
    self.add_transit(from_state=from_state, to_state=to_state, action=action, args=args,
                     ready=ready, act_id=act_id, avoid_changing_ready=avoid_changing_ready,
                     msg=msg, teleport=True, high_priority=high_priority,
                     total_time=total_time, timeout=timeout, delay=delay)

Calls add_transit() with teleport=True and the same arguments. A teleport behaves as an ordinary transition and differs only in the drawing and in the section where save() writes it.

add_global_teleport

add_global_teleport(to_state: str, action: str, args: dict | None = None, ready: bool = True, msg: str | None = None, high_priority: bool = False, total_time: float | str = 0.0, timeout: float | str = 0.0, delay: float | str = 0.0) -> None
Source code in unaiverse/hsm/hsm.py
def add_global_teleport(self, to_state: str,
                        action: str, args: dict | None = None, ready: bool = True,
                        msg: str | None = None,
                        high_priority: bool = False,
                        total_time: float | str = 0., timeout: float | str = 0., delay: float | str = 0., ) -> None:
    self.add_teleport(from_state=Custom.ALL_STATES_NAME, to_state=to_state, action=action, args=args,
                      ready=ready, act_id=None, high_priority=high_priority,
                      msg=msg, total_time=total_time, timeout=timeout, delay=delay)

Calls add_teleport() with from_state="all". The teleport therefore leaves every state that exists at the time of the call except to_state. A state created later does not get it. Here avoid_changing_ready stays False and an action with a parameter named interaction becomes request-only. A typical use is an exit that a world master can trigger from any state:

hsm.add_global_teleport("waiting", action="disengage", ready=False, high_priority=True)

include

include(hsm, make_a_copy=False) -> None
Source code in unaiverse/hsm/hsm.py
def include(self, hsm, make_a_copy=False) -> None:
    """Integrates the states and transitions of another state machine (`hsm`) into the current one. This is a
    crucial method for composing complex state machines from smaller, reusable components. It copies wildcards,
    states, and transitions, ensuring that all actions and states are properly added and linked. This method also
    handles an optional `make_a_copy` flag to completely replicate the source machine's state (e.g., current state,
    initial state).

    Args:
        hsm: The `HybridStateMachine` object to include.
        make_a_copy: A boolean to indicate whether the current state machine should adopt the state (e.g.,
            current state, initial state) of the included one.
    """

    # Copying wildcards
    self.add_wildcards(hsm.get_wildcards())

    # Adding states before adding transitions, so that we also add inner state actions, if any
    for _state in hsm.states.values():
        self.add_state(state=_state.name,
                       action=_state.action.name if _state.action is not None else None,
                       waiting_time=_state.waiting_time,
                       args=_state.action.args if _state.action is not None else None,
                       state_id=None,
                       blocking=_state.blocking,
                       msg=_state.msg_with_wildcards,
                       msg_action=_state.action.msg_with_wildcards if _state.action is not None else None)

    # Copy all the transitions of the HSM
    for _from_state, _to_states in hsm.transitions.items():
        for _to_state, _action_list in _to_states.items():
            for _action in _action_list:
                total_time = 0.
                timeout = 0.
                delay = 0.
                if isinstance(_action.get_total_time(), str) or _action.get_total_time() > 0:
                    total_time = _action.get_total_time()
                if isinstance(_action.get_timeout(), str) or _action.get_timeout() > 0.:
                    timeout = _action.get_timeout()
                if isinstance(_action.get_delay(), str) or _action.get_delay() > 0.:
                    delay = _action.get_delay()
                self.add_transit(from_state=_from_state, to_state=_to_state, action=_action.name,
                                 args=_action.args, ready=_action.ready, teleport=_action.is_teleport(),
                                 high_priority=_action.is_high_priority,
                                 act_id=None, msg=_action.msg_with_wildcards, avoid_changing_ready=True,
                                 total_time=total_time, timeout=timeout, delay=delay)

    if make_a_copy:
        self.state = hsm.state
        self.prev_state = hsm.prev_state
        self.initial_state = hsm.initial_state
        self.limbo_state = hsm.limbo_state
        self.set_welcome_message(hsm.welcome_msg_with_wildcards)
        self.show_blocking_states = hsm.show_blocking_states
        self.show_action_completion = hsm.show_action_completion
        self.show_action_request_info = hsm.show_action_request_info

Merges the machine hsm into this one and returns None. The wildcards of hsm are added to the wildcards of this machine. Every state of hsm goes through add_state() and replaces a state with the same name. Its transitions go through add_transit() with readiness, teleport flag, priority and timing preserved. A transition that already exists in this machine raises ValueError. The argument make_a_copy=True makes this machine take the current, previous, initial and limbo state of hsm as well as its welcome message and its three display options. add_transit() calls this method when to_state is a JSON path.

set_role

set_role(role: str) -> None
Source code in unaiverse/hsm/hsm.py
def set_role(self, role: str) -> None:
    """Sets the role of the agent associated with this state machine. This can be used to influence state machine
    behavior based on the agent's role (e.g., 'teacher', 'student').

    Args:
        role: The string representation of the new role.
    """
    self.role = role
    self.update_wildcard(Custom.ROLE_WILDCARD, role)
    self.apply_wildcards()

Stores role in the attribute role, writes it as the value of the wildcard <role> and applies all the wildcards. load() calls it with machine.role. Returns None.

set_welcome_message

set_welcome_message(msg: str | None) -> None
Source code in unaiverse/hsm/hsm.py
def set_welcome_message(self, msg: str | None) -> None:
    """Sets a message that will be printed only once when the initial state is reached."""

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

Stores the welcome message msg after decoding its HTML entities (&#128075; becomes the character it encodes). The value None removes the message. act() prints the message once when the machine is in its initial state and then removes it with set_welcome_message(None). Once the message has been printed, to_dict() and save() write "msg": null. Returns None.

Wildcard API

get_wildcards

get_wildcards() -> dict
Source code in unaiverse/hsm/hsm.py
def get_wildcards(self) -> dict:
    """Retrieves the dictionary of wildcards currently used by the state machine.

    Returns:
        A dictionary of the wildcards.
    """
    return self.wildcards

Returns the dictionary of wildcards itself and not a copy. A change made to it reaches every state and action of the machine at the next apply_wildcards().

set_wildcards

set_wildcards(wildcards: dict[str, str | float | int] | None, apply: bool = False) -> None
Source code in unaiverse/hsm/hsm.py
def set_wildcards(self, wildcards: dict[str, str | float | int] | None, apply: bool = False) -> None:
    """Sets the dictionary of wildcards that are used to dynamically replace placeholder values in action
    arguments.

    Args:
        wildcards: A dictionary containing wildcard key-value pairs.
        apply: True if the wildcards must be applied to whatever uses it (defaults to False)
    """
    wildcards = wildcards if wildcards is not None else {}

    # Saving wildcard dictionary, completely replacing the previous one
    self.wildcards = wildcards

    # Propagating the reference to the new dictionary to actions and states.
    for action in self.__id_to_action:
        action.set_wildcards(self.wildcards)
    for state in self.__id_to_state:
        state.set_wildcards(self.wildcards)

    if apply:
        self.apply_wildcards()

Replaces the whole dictionary of wildcards with wildcards (an empty one for None) and hands the new dictionary to every state and action. The four default wildcards are not added back. With apply=True the method also calls apply_wildcards() before returning None.

add_wildcards

add_wildcards(wildcards: dict[str, str | float | int | list[str]], apply: bool = False) -> None
Source code in unaiverse/hsm/hsm.py
def add_wildcards(self, wildcards: dict[str, str | float | int | list[str]], apply: bool = False) -> None:
    """Adds new key-value pairs to the existing wildcard dictionary.

    Args:
        wildcards: A dictionary of new wildcards to add.
        apply: True if the wildcards must be applied to whatever uses it (defaults to False).
    """

    # Update dictionary
    self.wildcards.update(wildcards)
    if apply:
        self.apply_wildcards()

Adds the entries of wildcards to the current dictionary and overwrites the keys that already exist. With apply=True the method also calls apply_wildcards() before returning None.

hsm.add_wildcards({"<learn_steps>": 40, "<exam_time>": 120}, apply=True)

update_wildcard

update_wildcard(wildcard_key: str, wildcard_value: str | float | int, apply: bool = False) -> None
Source code in unaiverse/hsm/hsm.py
def update_wildcard(self, wildcard_key: str, wildcard_value: str | float | int, apply: bool = False) -> None:
    """Updates the value of a single existing wildcard. It raises an error if the key does not exist. This method
    is useful for changing a single dynamic value without redefining all wildcards.

    Args:
        wildcard_key: The key of the wildcard to update.
        wildcard_value: The new value for the wildcard.
        apply: True if the wildcards must be applied to whatever uses it (defaults to False).
    """
    if wildcard_key not in self.wildcards:
        log.error(f"{wildcard_key} is not a valid wildcard")
    else:
        self.wildcards[wildcard_key] = wildcard_value
        if apply:
            self.apply_wildcards()

Changes the value of the existing wildcard wildcard_key to wildcard_value. An unknown key is logged as an error and leaves the dictionary unchanged. With apply=True the method also calls apply_wildcards(). The node uses it for <agent>, <world> and <partner>. Returns None.

apply_wildcards

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

    # Propagating the reference to the new dictionary to actions and states.
    for action in self.__id_to_action:
        action.apply_wildcards()
    for state in self.__id_to_state:
        state.apply_wildcards()

    # If there is a welcome message that includes wildcards...
    if self.welcome_msg is not None:
        self.welcome_msg = self.welcome_msg_with_wildcards  # Restore before updating
        for wildcard_from, wildcard_to in self.wildcards.items():
            self.welcome_msg = self.welcome_msg.replace(wildcard_from, str(wildcard_to))  # Update

Applies the current wildcards to every action and state of the machine and to the welcome message. Because each object starts again from its original arguments and messages, a second call with different values gives the result of the second call alone. The rules of the replacement are in Wildcards. The system interaction of each action is rebuilt with the resolved values. Returns None.

Running the machine

act async

act() -> bool
Source code in unaiverse/hsm/hsm.py
async def act(self) -> bool:
    """A high-level method that combines `act_states` and `act_transitions` to run the state machine. It repeatedly
    processes states and transitions until a blocking state is reached or all feasible actions have been tried,
    thus ensuring a complete processing cycle in one call (async).

    Returns:
        True if, during this whole 'act', the state changed at least once.
    """

    # It keeps processing states and actions, until all the current feasible actions fail
    # (also when a step of a multistep action is executed) or a blocking state is reached
    changed_state = False
    starting_state = self.state
    while True:
        if self.welcome_msg is not None and self.state is not None and self.state == self.initial_state:
            log.user(self.welcome_msg)
            self.set_welcome_message(None)

        await self.act_states()
        ret = await self.act_transitions(self.must_wait())
        if self.state != starting_state:  # Value of self.state might change while act_transitions runs
            changed_state = True
        if ret != 0 or (self.state is not None and self.states[self.state].blocking):
            break
    return changed_state

Runs one cycle of the machine as described in One call of act(). The coroutine returns True when at least one pass of the loop leaves the machine in a state other than the one it had at the start of the call. A path that comes back to the starting state counts as a change. An action left running (code 1) counts as a change too because the current state is None while it runs. The agent awaits it at every clock cycle, first on agent.behav while it is in a world and then on agent.behav_lone_wolf. Exceptions raised by the policy or by the argument resolution propagate to the caller. An exception raised inside an @action method does not propagate because the decorator turns it into False.

act_states async

act_states() -> None
Source code in unaiverse/hsm/hsm.py
async def act_states(self) -> None:
    """Executes the inner action of the current state, if one exists. This method is for actions that occur upon
    entering a state but do not cause an immediate transition. It only runs if the state machine is enabled (async).
    """
    if not self.enabled:
        return

    if self.state is not None:  # When in the middle of an action, the state is Nones
        await self.states[self.state]()  # Run the action (if any)

Runs the action of the current state when the machine is enabled and no action is running. The coroutine discards the return value of the state action and returns None.

act_transitions async

act_transitions(only_the_ones_with_interactions: bool = False) -> int
Source code in unaiverse/hsm/hsm.py
async def act_transitions(self, only_the_ones_with_interactions: bool = False) -> int:
    """This is the core execution loop for transitions. It finds all feasible actions from the current state and,
    using a policy, selects and executes one. It handles single-step and multistep actions, managing state changes,
    timeouts, and failed executions. It returns an integer status code indicating the outcome (e.g., transition
    done, try again, move to next action) (async).

    Args:
        only_the_ones_with_interactions: A boolean to consider only actions that have pending interactions.

    Returns:
        An integer status code: `0` for a successful transition, `1` to retry the same action, `2` to move to the
        next action, or `-1` if no actions were found.
    """
    if not self.enabled:
        return -1

    # Collecting list of feasible actions, wait flags, etc. (from the current state)
    if self.__cur_feasible_actions_status is None:
        if self.state is None:
            return -1

        actions_list = []
        to_state_list: list[str] = []
        attempts_to_serve_an_interaction_list = []

        for to_state, action_list in self.transitions[self.state].items():
            for i, action in enumerate(action_list):

                # Checking is_ready will check if streams are ready and if the interaction was completed meanwhile
                if (action.is_ready(consider_interactions=True,
                                    delay_starting_time=self.states[self.state].starting_time) and
                        (not only_the_ones_with_interactions or
                         len(action.interactions.get_interactions(doable_only=True)) > 0)):
                    actions_list.append(action)
                    to_state_list.append(to_state)
                    attempts_to_serve_an_interaction_list.append(0)

        if len(actions_list) > 0:
            self.__cur_feasible_actions_status = {
                'actions_list': actions_list,
                'to_state_list': to_state_list,
                'selected_idx': 0,
                'selected_interaction': None,
                'attempts_to_serve_an_interaction_list': attempts_to_serve_an_interaction_list
            }
    else:

        # Reloading the already computed set of actions, wait flags, etc. (when in the middle of an action)
        actions_list = self.__cur_feasible_actions_status['actions_list']
        to_state_list: list[str] = self.__cur_feasible_actions_status['to_state_list']
        attempts_to_serve_an_interaction_list: list[int] = (
            self.__cur_feasible_actions_status)['attempts_to_serve_an_interaction_list']

    # If action_list is empty, then self.__cur_feasible_actions_status stays None, and the loop below is not
    # considered at all. If action_list is not empty, then self.__cur_feasible_actions_status must have been
    # initialized (dict)
    assert len(actions_list) == 0 or isinstance(self.__cur_feasible_actions_status, dict)

    # Using the selected policy to decide what action to apply
    while len(actions_list) > 0:
        skip_action_due_to_filter = False

        # It there was an already selected action (for example a multistep action), then continue with it,
        # otherwise, select a new one following a certain policy (actually, first-come first-served)
        if self.__action is None:
            log.statem(f"List of actions to choose from:\n   " +
                       "\n   ".join([a.to_code_str().replace("\n", "\n   ")
                                     for a in actions_list]), state=self.get_state_name())

            # Naive policy: take the first action that is ready
            _idx, _interaction = self.policy(actions_list)

            if _idx < 0:
                log.statem(f"Selected no actions", state=self.get_state_name())

                # No actions were applied
                self.__cur_feasible_actions_status = None
                self.__state_changed = False
                return -1  # Early stop
            else:
                if _interaction is not None:
                    log.statem(f"Selected {actions_list[_idx].to_code_str()}, "
                               f"{_interaction.to_code_str(True)}",
                               state=self.get_state_name())
                else:
                    log.statem(f"Selected {actions_list[_idx].to_code_str()}, no-interactions",
                               state=self.get_state_name())

            # Revisiting decisions due to the policy filter
            if self.policy_filter is not None:
                try:
                    _idx_f, _interactions_f = self.policy_filter(_idx, _interaction,
                                                                 actions_list, self.policy_filter_opts)

                    # Keep this part of code: needed to stabilize potential object duplicates (JS)
                    if _interactions_f != _interaction and _interactions_f is not None:
                        _interactions_f = self.agent.im.get_interaction(uuid=_interactions_f.uuid)
                except Exception as e:
                    log.error(f"Skipping policy filter due to exception: {e}",
                              state=self.get_state_name())
                    _idx_f = _idx
                    _interactions_f = _interaction

                if _idx_f != _idx or _interactions_f != _interaction:
                    if _idx_f < 0:
                        log.statem(f"Filter selected no actions among {[a.name for a in actions_list]}")

                        # No actions were applied
                        # self.__cur_feasible_actions_status = None
                        # self.__state_changed = False
                        # return -1  # Early stop
                        skip_action_due_to_filter = True
                    else:
                        _idx = _idx_f
                        _interaction = _interactions_f

                        if _interaction is not None:
                            log.statem(
                                f"Filter selected {actions_list[_idx].to_code_str()}, {_interaction.__str__()}",
                                state=self.get_state_name())
                        else:
                            log.statem(f"Filter selected {actions_list[_idx].to_code_str()}, "
                                       f"no-interactions", state=self.get_state_name())
                else:
                    log.statem(f"Filter confirmed the selection", state=self.get_state_name())

            # Saving current action
            self.limbo_state = self.state
            self.state = None
            self.__action = actions_list[_idx]

            assert self.__action is not None

            # Forcing system interaction if no external interactions were selected
            if _interaction is None:
                _interaction = self.__action.system_interaction

            _interaction.reset_state()  # Resetting
            assert self.__cur_feasible_actions_status is not None
            self.__cur_feasible_actions_status['selected_idx'] = _idx
            self.__cur_feasible_actions_status['selected_interaction'] = _interaction

        # References
        assert self.__cur_feasible_actions_status is not None
        action = self.__action
        idx = self.__cur_feasible_actions_status['selected_idx']
        interaction: Interaction = self.__cur_feasible_actions_status['selected_interaction']

        assert interaction is not None

        # If this action has an associated Interaction, set it as current on the IM
        # (this configures stdin/stdout for the action)
        # If the Interaction is (1) None, or (2) a system interaction with no streams at all, or
        # (3) a received interaction with no streams, then the stdin/stdout/... will be set back to default streams
        if self.agent.im.current is None or self.agent.im.current != interaction:
            self.agent.im.set_current(interaction)

        log.statem(f">>> ACTION {action.name}...", state=self.get_state_name(True))
        if len(action.get_list_of_interactions()) > 0:
            log.statem(str(action.get_list_of_interactions()))

        # Calling action, getting back status.
        # Status can be one of these:
        # 0: action fully done;
        # 1: try again this action;
        # 2: failed, move to another action.
        status = (await action(interaction=interaction)) if not skip_action_due_to_filter else 2  # noqa

        if status == 0:
            log.statem(f"+++ ACTION {action.name} correctly completed", state=self.get_state_name(True))
        elif status == 1:
            log.statem(f"~~~ ACTION {action.name} will be run again", state=self.get_state_name(True))
        else:
            log.statem(f"--- ACTION {action.name} failed", state=self.get_state_name(True))

        if action.msg is not None and self.show_action_completion:
            log.user(Custom.ACTION_TICKS_PER_STATUS[status])

        # Post-call operations
        if status == 0:  # Done

            # State transition
            self.prev_state = self.limbo_state
            idx: int
            self.state = to_state_list[idx]
            self.limbo_state = None

            # Complete the associated Interaction (if any) via Interaction Manager (IM)
            # The Interaction Manager on the agent (agent) will handle the completion, saving the destination state
            await self.agent.im.complete_current(self.state, CompletionReason.OK)

            # Update status
            self.__state_changed = self.state != self.prev_state  # Checking if we are on a self-loop or not
            self.__last_completed_action = self.__action  # This will be set also if the state does not change

            # If we moved to another state
            # (this is not true anymore: "clearing all the pending annotations for the next possible actions")
            if self.__state_changed:
                log.statem(f">>> MOVING TO STATE: {self.state}", state=self.get_state_name())
                # for to_state, action_list in self.transitions[self.state].items():
                #    for i, act in enumerate(action_list):
                #        act.clear_requests()

            self.states[self.prev_state].reset(self.__state_changed)  # Reset starting time

            # The message of an action is printed once per series of attempts: a new series starts once it is done,
            # and, for every action of the state that was left, when the machine comes back to that state
            action.reset_msg_printing()
            if self.__state_changed:
                self.__reset_msg_printing(self.prev_state)
            interaction.reset_state()
            self.__action = None  # Clearing
            self.__cur_feasible_actions_status = None

            return 0  # Transition done, no need to check other actions!

        elif status == 1:  # Try again the same action (either a new step or an already done-and-failed one)

            # Update status
            self.__state_changed = False
            # if self.prev_state is not None:
            #    self.states[self.prev_state].reset()  # Reset starting time

            return 1  # Transition not-done: no need to check other actions, the current one will be run again

        elif status == 2:  # Move to the next action (or to the next request of the same action)

            # Clearing request
            assert self.__action is not None
            self.__action.interactions.move_interaction_to_back(interaction)  # Rotating to avoid starvation
            attempts_to_serve_an_interaction_list[idx] += 1

            # Back to the original state
            self.state = self.limbo_state
            self.limbo_state = None

            # Purging action from the current list
            attempts_to_serve_an_interaction_list: list[int]
            if attempts_to_serve_an_interaction_list[idx] >= len(self.__action.get_list_of_interactions()):
                del actions_list[idx]
                del to_state_list[idx]
                del attempts_to_serve_an_interaction_list[idx]

            # Update status
            self.__state_changed = False
            interaction.reset_state()
            self.agent.im.set_current_as_paused()
            self.__action = None  # Clearing

            continue  # Move to the next action
        else:
            raise ValueError("Unexpected status: " + str(status))

    # No actions were applied
    self.__cur_feasible_actions_status = None
    self.__state_changed = False
    return -1

Collects the feasible actions of the current state, asks the policy and the filter for a choice and runs the chosen action. After each discarded attempt it asks the policy again. An action that returned code 1 at the previous call is resumed without collecting candidates. The argument only_the_ones_with_interactions=True keeps only the actions with a pending request that can be served now.

The coroutine returns 0 when a transition completed and 1 when the running action must run again at the next call. It returns -1 in five cases: (1) the machine is disabled, (2) it has no current state, (3) no action is feasible, (4) the policy chose nothing and (5) every candidate was discarded. It never returns 2. An action code other than 0, 1 and 2 raises ValueError.

act_ghost_transition async

act_ghost_transition(to_state: str) -> int
Source code in unaiverse/hsm/hsm.py
async def act_ghost_transition(self, to_state: str) -> int:

    # Forcing to go back to current state if in the middle of a multistep action
    from_state = self.state
    if from_state is None:
        from_state = self.limbo_state
    self.set_state(from_state)  # This will also reset the current interaction (if any)

    # Setting up the ghost action (nop) as only possible action from the current state
    original_transitions = self.transitions[from_state]
    self.transitions[from_state] = \
        {to_state: [Action(name="nop", args={}, agent=self.agent, ready=True, teleport=True)]}

    # Acting the ghost action (nop)
    ret = await self.act_transitions()

    # Restoring original transitions
    self.transitions[from_state] = original_transitions
    return ret

Moves the machine to to_state through a hidden nop action. The method first brings the machine back to its current state (the limbo state when an action is running) and drops the running action in doing so. It then replaces the transitions of that state with a single nop teleport to to_state, runs act_transitions(), restores the original transitions and returns the code of act_transitions(). The agent must have a nop action as every Agent has. The method does not check that to_state exists. The SDK never calls this coroutine.

must_wait

must_wait() -> bool
Source code in unaiverse/hsm/hsm.py
def must_wait(self) -> bool:
    """Checks if the current state is in a waiting period before any transitions can occur.

    Returns:
        A boolean indicating if the state machine must wait.
    """
    if self.state is not None:
        return self.states[self.state].must_wait()
    else:
        return False

Returns True while the current state is within its time_to_wait_before_acting. The result is False in three cases: (1) the time has passed, (2) the state has no waiting time and (3) an action is running. act() passes the result to act_transitions().

enable

enable(yes_or_not: bool) -> None
Source code in unaiverse/hsm/hsm.py
def enable(self, yes_or_not: bool) -> None:
    """Enables or disables the state machine. When disabled, the `act_states` and `act_transitions` methods will
    not perform any actions.

    Args:
        yes_or_not: A boolean to enable (`True`) or disable (`False`) the state machine.
    """
    self.enabled = yes_or_not

Enables (True) or disables (False) the machine and returns None. A disabled machine ignores act_states() and act_transitions(). The agent enables each of its two machines only while it runs it.

is_enabled

is_enabled() -> bool
Source code in unaiverse/hsm/hsm.py
def is_enabled(self) -> bool:
    """A simple getter to check if the state machine is currently enabled to run.

    Returns:
        True if the state machine is enabled, False otherwise.
    """
    return self.enabled

Returns the attribute enabled.

get_state_changed

get_state_changed() -> bool
Source code in unaiverse/hsm/hsm.py
def get_state_changed(self) -> bool:
    """Returns an internal flag that indicates if a state transition has occurred in the last execution cycle.
    This can be used by an external loop to know when to re-evaluate the state machine's context.

    Returns:
        True if the state has changed, False otherwise.
    """
    return self.__state_changed

Returns True when the last completed transition moved the machine to a different state. A self-loop, a code 1 or 2 and a call where nothing ran all leave the flag at False.

Requests from other agents

request_action

request_action(interaction: Interaction) -> bool
Source code in unaiverse/hsm/hsm.py
def request_action(self, interaction: Interaction) -> bool:
    """Allows an external entity to request a specific action. The request is validated by a signature checker
    (if one exists) and then queued on the corresponding action. This method enables dynamic, external triggers for
    state machine transitions.

    Args:
        interaction: The interaction object.

    Returns:
        True if the request was accepted and queued, False otherwise.
    """
    log.misc(f"Received an action request with this interaction: {interaction}", state=self.get_state_name())

    # Getting data
    action_name = interaction.action_name
    args = interaction.action_kwargs

    if action_name is None:
        log.error(f"Requested an action with no name!")
        return False

    # If state is not provided, the current state is assumed
    from_state = interaction.from_state
    if from_state is None:
        # If the request arrives in the middle of a multistep action, we need to check limbo state
        from_state = self.state if self.state is not None else self.limbo_state
    if from_state not in self.transitions:
        log.error(f"Request not accepted: not valid source state ({from_state})",
                  state=self.get_state_name())
        return False

    # If the destination state is not provided, all the possible destination from the current state are considered
    to_state = interaction.to_state
    if to_state is not None and to_state not in self.transitions[from_state]:
        log.error(f"Request not accepted: not valid destination state ({to_state})",
                  state=self.get_state_name())
        return False
    to_states = self.transitions[from_state].keys() if to_state is None else [to_state]

    for to_state in to_states:
        action_list = self.transitions[from_state][to_state]
        for i, action in enumerate(action_list):
            if action.same_as(name=action_name, args=args):
                log.misc(f"Requested action ({action_name}) found in state {from_state}, "
                         f"adding interaction to the queue",
                         state=self.get_state_name())

                # Action found, let's save the suggestion
                if action.add_interaction(interaction):
                    return True
                else:
                    log.error("Requested action does not allow interactions")
                    return False  # If the action does not support interactions

    # If the action was not found
    log.error(f"Requested action ({action_name}) not found "
              f"(from_state={from_state}, cur_state={self.get_state_name()})",
              state=self.get_state_name())
    return False

Queues the Interaction of another agent on the matching action. The agent calls it when a request arrives. The method reads interaction.action_name, interaction.action_kwargs, interaction.from_state and interaction.to_state. A missing from_state stands for the current state (the limbo state while an action runs) and a missing to_state stands for every destination of from_state. The first action that is same_as the requested name and arguments receives the interaction through add_interaction.

The method returns True when the interaction was queued. It logs the reason and returns False when the name is missing, the source or destination state is unknown, no action matches or the matching action does not accept requests.

transition_exists

transition_exists(name: str, only_ready: bool = True) -> bool
Source code in unaiverse/hsm/hsm.py
def transition_exists(self, name: str, only_ready: bool = True) -> bool:
    state = self.state if self.state is not None else self.limbo_state
    trans = self.transitions[state]
    for _, action_list in trans.items():
        for action in action_list:
            if (not only_ready or action.is_ready()) and action.name == name:
                return True
    return False

Returns True when a transition that leaves the current state (or the limbo state) has the action name. The default only_ready=True counts only the actions that are ready now or have a request that can be served now.

wait_for_all_actions_that_start_with

wait_for_all_actions_that_start_with(prefix: str) -> None
Source code in unaiverse/hsm/hsm.py
def wait_for_all_actions_that_start_with(self, prefix: str) -> None:
    """Sets the `ready` flag to `False` for all actions whose name begins with a given prefix. This method is used
    to programmatically disable a group of actions, effectively pausing them.

    Args:
        prefix: The string prefix to match against action names.
    """
    for state, to_states in self.transitions.items():
        for to_state, action_list in to_states.items():
            for i, action in enumerate(action_list):
                if action.name.startswith(prefix):
                    action.set_as_not_ready()

Calls set_as_not_ready on every transition action whose name starts with prefix and thus makes these actions request-only. State actions are not touched. Returns None.

wait_for_all_actions_that_include_an_arg

wait_for_all_actions_that_include_an_arg(arg_name: str) -> None
Source code in unaiverse/hsm/hsm.py
def wait_for_all_actions_that_include_an_arg(self, arg_name: str) -> None:
    """Sets the `ready` flag to `False` for all actions that include a specific argument name in their signature.
    This provides another way to programmatically disable actions.

    Args:
        arg_name: The name of the argument to look for.
    """
    for state, to_states in self.transitions.items():
        for to_state, action_list in to_states.items():
            for i, action in enumerate(action_list):
                if arg_name in action.args:
                    action.set_as_not_ready()

Makes request-only every transition action whose arguments in the behavior (action.args) contain the key arg_name. A parameter of the method that the transition leaves out of its arguments does not count. Returns None.

Current state and action

get_state_name

get_state_name(consider_limbo: bool = False) -> str | None
Source code in unaiverse/hsm/hsm.py
def get_state_name(self, consider_limbo: bool = False) -> str | None:
    """Retrieves the name of the current state of the state machine.

    Args:
        consider_limbo: If True and the current state is None (mid-transition), returns the limbo state
            name instead.

    Returns:
        A string with the state's name, or ``None`` if no state is set.
    """

    if not consider_limbo:
        return self.state
    else:
        if self.state is None and self.limbo_state is not None:
            return self.limbo_state
        else:
            return self.state

Returns the name of the current state. While an action runs the current state is None and consider_limbo=True makes the method return the source state of the running action instead.

get_state

get_state() -> State | None
Source code in unaiverse/hsm/hsm.py
def get_state(self) -> 'State | None':
    """Retrieves the current `State` object of the state machine.

    Returns:
        A `State` object or `None`.
    """
    return self.states[self.state] if self.state is not None else None

Returns the State object of the current state. The result is None while an action runs.

get_states

get_states() -> list
Source code in unaiverse/hsm/hsm.py
def get_states(self) -> list:
    """Returns an iterable of all state names defined in the state machine.

    Returns:
        An iterable of state names.
    """
    return [s.name for s in self.__id_to_state]

Returns the list of the state names in the order in which they were added.

get_all_states

get_all_states() -> list[State]
Source code in unaiverse/hsm/hsm.py
def get_all_states(self) -> list['State']:
    """Retrieves the list of all `State` objects.

    Returns:
        List of `State` objects.
    """
    return self.__id_to_state

Returns the internal list of State objects indexed by state id. The list is not a copy.

get_all_actions

get_all_actions() -> list[Action]
Source code in unaiverse/hsm/hsm.py
def get_all_actions(self) -> list['Action']:
    """Retrieves the list of all `Action` objects.

    Returns:
        List of `Action` objects.
    """
    return self.__id_to_action

Returns the internal list, indexed by action id, of every Action ever created by the machine with the state actions included. An action replaced by add_state() stays in the list.

get_action

get_action() -> Action | None
Source code in unaiverse/hsm/hsm.py
def get_action(self) -> 'Action | None':
    """Retrieves the `Action` object that is currently being executed.

    Returns:
        An `Action` object or `None`.
    """
    return self.__action

Returns the running Action or None when no action runs.

get_action_name

get_action_name() -> str | None
Source code in unaiverse/hsm/hsm.py
def get_action_name(self) -> str | None:
    """Retrieves the name of the action currently being executed.

    Returns:
        A string with the action's name, or `None` if no action is running.
    """
    return self.__action.name if self.__action is not None else None

Returns the name of the running action or None when no action runs. The agent records it in its statistics as action.

get_last_completed_action_name

get_last_completed_action_name() -> str | None
Source code in unaiverse/hsm/hsm.py
def get_last_completed_action_name(self) -> str | None:
    """Retrieves the name of the last action that was correctly executed.

    Returns:
        A string with the action's name, or `None` if no actions were executed before.
    """
    return self.__last_completed_action.name if self.__last_completed_action is not None else None

Returns the name of the last action that returned code 0 (self-loops included) or None before the first one. The agent records it in its statistics as last_action.

get_action_step_idx

get_action_step_idx() -> int
Source code in unaiverse/hsm/hsm.py
def get_action_step_idx(self) -> int:
    """Retrieves the current step index of the action being executed. This is particularly useful for tracking the
    progress of multistep actions.

    Returns:
        An integer representing the current step, or -1 if no action is running.
    """
    assert self.__action is None or isinstance(self.__cur_feasible_actions_status, dict)
    if self.__action is None:
        return -1
    else:
        assert isinstance(self.__cur_feasible_actions_status, dict)
        return self.__cur_feasible_actions_status['selected_interaction'].get_step_idx()

Returns the step index of the interaction served by the running action. The index is -1 before the first step and when no action runs, 0 during or after the first step and so on. The agent exposes it to actions through get_action_step().

is_busy_acting

is_busy_acting() -> bool
Source code in unaiverse/hsm/hsm.py
def is_busy_acting(self) -> bool:
    """Checks if the state machine is currently executing an action. This is determined by checking if the action
    step index is greater than or equal to 0.

    Returns:
        True if an action is running, False otherwise.
    """
    return self.get_action_step_idx() >= 0

Returns True when get_action_step_idx() is 0 or more. This happens when a running action has started at least one step.

get_time_spent_in_current_state

get_time_spent_in_current_state()
Source code in unaiverse/hsm/hsm.py
def get_time_spent_in_current_state(self):
    state = self.state
    if state is None:
        state = self.limbo_state
    if state is None:
        return -1.
    else:
        return self.states[state].get_time_passed()

Returns the seconds spent in the current state (the limbo state while an action runs) since the first pass of act_states() after entering it. The result is -1. when there is no state or the state has not been entered yet.

set_state

set_state(state: str) -> None
Source code in unaiverse/hsm/hsm.py
def set_state(self, state: str) -> None:
    """Sets the current state of the state machine to a new, specified state. It also handles the transition logic
    by resetting the current action and updating the previous state. Raises an error if the new state is not known
    to the machine.

    Args:
        state: The name of the state to transition to.
    """
    if state in self.transitions or state in self.states:
        self.limbo_state = None
        self.prev_state = self.state
        self.state = state
        if self.prev_state != state:
            self.__reset_msg_printing(self.prev_state)
        if self.__action is not None:
            assert isinstance(self.__cur_feasible_actions_status, dict)
            self.__cur_feasible_actions_status['selected_interaction'].reset_state()
            self.__action = None
            self.__cur_feasible_actions_status = None
        if self.initial_state is None:
            self.initial_state = state
    else:
        raise ValueError("Unknown state: " + str(state))

Moves the machine to state without running any action. The previous state becomes prev_state, the limbo state is cleared and a running action is dropped together with the progress of its interaction. The message of every action that leaves the previous state can be printed again. When the machine has no initial state, state becomes the initial state. A state unknown to the machine raises ValueError("Unknown state: ..."). Returns None.

reset_state

reset_state() -> None
Source code in unaiverse/hsm/hsm.py
def reset_state(self) -> None:
    """Resets the state machine to its initial state. This clears the current action, the previous state, and
    the limbo state. It also resets the step counters for all actions within the machine.
    """
    self.state = self.initial_state
    self.limbo_state = None
    self.prev_state = None
    self.__action = None
    self.__cur_feasible_actions_status = None
    for act in self.__id_to_action:
        act.clear_interactions()
        act.system_interaction.reset_state()
        act.reset_msg_printing()
    for s in self.__id_to_state:
        s.reset()
        if s.action is not None:
            s.action.clear_interactions()
            s.action.system_interaction.reset_state()

Brings the machine back to initial_state, clears the previous and limbo state and the running action and resets every state and action. The pending requests of every action are deleted. Returns None.

Messages and debugging

show_ticks_in_action_messages

show_ticks_in_action_messages(do_it: bool = True) -> None
Source code in unaiverse/hsm/hsm.py
def show_ticks_in_action_messages(self, do_it: bool = True) -> None:
    """Enables or disables tick symbols appended to action log messages upon completion."""
    self.show_action_completion = do_it

Turns the option show_action_ticks_after_messages on (do_it=True) or off. When the option is on, every attempt of an action with a message is followed in the user log by ✅ (code 0), 🔄 (code 1) or ❌ (code 2). Returns None.

show_marks_in_blocking_state_messages

show_marks_in_blocking_state_messages(do_it: bool = True) -> None
Source code in unaiverse/hsm/hsm.py
def show_marks_in_blocking_state_messages(self, do_it: bool = True) -> None:
    """Enables or disables colored markers (🔴/🟢) appended to blocking-state log messages."""
    self.show_blocking_states = do_it

Turns the option highlight_blocking_states_in_messages on or off. When the option is on, the message of a blocking state ends with 🔴 and the message of a non-blocking state with 🟢. Returns None.

show_request_info_in_action_messages

show_request_info_in_action_messages(do_it: bool = True) -> None
Source code in unaiverse/hsm/hsm.py
def show_request_info_in_action_messages(self, do_it: bool = True) -> None:
    """Enables or disables requester/UUID info appended to action log messages."""
    self.show_action_request_info = do_it

Turns the option show_action_request_after_messages on or off. When the option is on, the message of an action ends with the requester, the interaction uuid and the number of pending interactions. Returns None.

set_debug_messages_active

set_debug_messages_active(yes: bool) -> None
Source code in unaiverse/hsm/hsm.py
def set_debug_messages_active(self, yes: bool) -> None:
    """Activates or deactivates debug mode, enabling ticks, blocking marks, request info, and auto-labels.

    Args:
        yes: True to enable debug mode, False to restore original messages and disable extra info.
    """
    self.__debug_messages_active = yes

    if yes:
        self.show_ticks_in_action_messages(True)
        self.show_marks_in_blocking_state_messages(True)
        self.show_request_info_in_action_messages(True)

        # Replace original messages
        self.generate_auto_messages(force=True)
    else:
        self.show_ticks_in_action_messages(False)
        self.show_marks_in_blocking_state_messages(False)
        self.show_request_info_in_action_messages(False)

        # Restore original messages
        if len(self.__id_to_original_state_msg) > 0:
            for i, state in enumerate(self.__id_to_state):
                state.set_msg(self.__id_to_original_state_msg[i][0])
                if state.action is not None:
                    state.action.set_msg(self.__id_to_original_state_msg[i][1])
        if len(self.__id_to_original_action_msg) > 0:
            for i, action in enumerate(self.__id_to_action):
                action.set_msg(self.__id_to_original_action_msg[i])
        self.__id_to_original_state_msg.clear()
        self.__id_to_original_action_msg.clear()

        # Apply wildcards to the restored messages
        self.apply_wildcards()

With yes=True the method turns on the three display options and replaces every message with a generated one through generate_auto_messages(force=True). With yes=False it turns the options off, restores the original messages and applies the wildcards again. The node calls it when its debug mode changes. Returns None.

are_debug_messages_active

are_debug_messages_active() -> bool
Source code in unaiverse/hsm/hsm.py
def are_debug_messages_active(self) -> bool:
    """Returns whether debug messages (auto-generated labels, ticks, marks) are currently active."""
    return self.__debug_messages_active

Returns whether set_debug_messages_active(True) is in effect.

generate_auto_messages

generate_auto_messages(states: bool = True, actions: bool = True, force: bool = False) -> None
Source code in unaiverse/hsm/hsm.py
def generate_auto_messages(self, states: bool = True, actions: bool = True, force: bool = False) -> None:
    """Auto-generates human-readable messages for states and actions that currently have none.

    Args:
        states: If True, generates messages for states (and their inner actions).
        actions: If True, generates messages for transition actions.
        force: If True, overwrites existing messages, appending the original text in brackets.
    """
    if states is True and len(self.__id_to_original_state_msg) == 0:
        for state in self.__id_to_state:
            original1 = state.msg_with_wildcards
            original2 = state.action.msg_with_wildcards if state.action is not None else None

            if state.msg_with_wildcards is None:
                state.set_msg("📍 " + state.name.replace('_', ' ').capitalize())
            elif force:
                state.set_msg("📍 " + state.name.replace('_', ' ').capitalize() +
                              " [" + state.msg_with_wildcards + "]")
            if state.action is not None:
                if state.action.msg_with_wildcards is None:
                    state.action.set_msg("📍 " + state.action.name.replace('_', ' ').capitalize())
                elif force:
                    state.action.set_msg("📍 " + state.action.name.replace('_', ' ').capitalize() +
                                         " [" + state.action.msg_with_wildcards + "]")

            self.__id_to_original_state_msg.append((original1, original2))
    if actions is True and len(self.__id_to_original_action_msg) == 0:
        for action in self.__id_to_action:
            original = action.msg_with_wildcards

            if action.msg_with_wildcards is None:
                action.set_msg("🚀 " + action.name.replace('_', ' ').capitalize())
            elif force:
                action.set_msg("🚀 " + action.name.replace('_', ' ').capitalize() +
                               " [" + action.msg_with_wildcards + "]")

            self.__id_to_original_action_msg.append(original)

Generates a message from the name of each state and action without one: the state exam_prepared gets 📍 Exam prepared and the action send_engage gets 🚀 Send engage. With force=True existing messages are replaced too and keep the original text in brackets. The flags states and actions choose which objects are touched. The method remembers the original messages for set_debug_messages_active(False) and a second call does nothing until they are restored. Returns None.

print_actions

print_actions(state: str | None = None) -> None
Source code in unaiverse/hsm/hsm.py
def print_actions(self, state: str | None = None) -> None:
    """Prints a list of all transitions and their associated actions from a given state. If no state is provided,
    it defaults to the current state. This method is useful for quickly inspecting the available transitions from
    a specific point in the state machine's flow.

    Args:
        state: The name of the state from which to print actions. Defaults to the current state.
    """
    state = (self.state if self.state is not None else self.limbo_state) if state is None else state
    assert state is not None
    for to_state, action_list in self.transitions[state].items():
        if action_list is None or len(action_list) == 0:
            log.user(f"{state}, no actions")
        else:
            for action in action_list:
                log.user(f"{state} --> {to_state} {action}")

Prints through the user log channel one line per action for every transition that leaves state (the current or limbo state when state is None). Returns None.

Persistence and drawing

to_dict

to_dict() -> dict
Source code in unaiverse/hsm/hsm.py
def to_dict(self) -> dict:
    """Serializes the state machine's current configuration into a dictionary. This includes its states,
    transitions, roles, and the current action being executed. It is useful for saving the state of the machine or
    for logging its status in a structured format.

    Returns:
        A dictionary representation of the state machine's properties.
    """

    # Inverting the organization of the transition matrix, and considering teleport actions only
    teleport_inv_transitions = {}
    action_that_are_teleports = []
    for src, dests in self.transitions.items():
        for dest, actions in dests.items():
            if dest == src:
                continue  # Skipping self loops for teleports (they should not be there at all, if so, we filter)
            for act in actions:
                if act.is_teleport():
                    action_that_are_teleports.append(act)
                    if dest not in teleport_inv_transitions:
                        teleport_inv_transitions[dest] = {}
                    if src not in teleport_inv_transitions[dest]:
                        teleport_inv_transitions[dest][src] = []
                    teleport_inv_transitions[dest][src].append(act)

    # Parsing destination states: if the same action connects this to all the possible states, then it is an
    # "all"-like teleport
    teleport_transitions = {Custom.ALL_STATES_NAME: {}}  # Keep "all" on top (it is handled like a new state)
    for dest, srcs in teleport_inv_transitions.items():

        # For each source state reaching the current destination...
        for src, teleports in srcs.items():

            # For each teleport linking source to the current destination...
            for tel in teleports:
                if tel.get_mark() == "considered":  # Skipping already considered ones
                    continue

                tel.set_mark("considered")  # Marking
                tel_to_list = tel.to_list()
                _found_teleports = [(src, tel)]

                # Let's see if a teleport equivalent to the considered one connects all sources
                for _src, _teleports in srcs.items():
                    if src == _src:
                        continue  # Already considered case

                    _found = False
                    for _tel in _teleports:
                        if _tel.get_mark() == "considered":  # Skipping already considered ones
                            continue

                        if tel_to_list == _tel.to_list():
                            _tel.set_mark("considered")  # Marking
                            _found_teleports.append((_src, _tel))
                            _found = True
                            break
                    if not _found:
                        break

                # Distinguishing
                if len(_found_teleports) == (len(self.states) - 1):
                    if Custom.ALL_STATES_NAME not in teleport_transitions:
                        teleport_transitions[Custom.ALL_STATES_NAME] = {}
                    if dest not in teleport_transitions[Custom.ALL_STATES_NAME]:
                        teleport_transitions[Custom.ALL_STATES_NAME][dest] = []
                    teleport_transitions[Custom.ALL_STATES_NAME][dest].append(tel)  # Append a single one
                else:
                    for _src, _tel in _found_teleports:
                        if _src not in teleport_transitions:
                            teleport_transitions[_src] = {}
                        if dest not in teleport_transitions[_src]:
                            teleport_transitions[_src][dest] = []
                        teleport_transitions[_src][dest].append(_tel)

    # Clearing mark
    for tel in action_that_are_teleports:
        tel.clear_mark()

    return {
        'machine': {
            'role': self.role,
            'initial_state': self.initial_state,
            'msg': self.welcome_msg_with_wildcards.encode("ascii", "xmlcharrefreplace").decode(
                    "ascii") if self.welcome_msg_with_wildcards is not None else None,
            'options': {
                'highlight_blocking_states_in_messages': self.show_blocking_states,
                'show_action_ticks_after_messages': self.show_action_completion,
                'show_action_request_after_messages': self.show_action_request_info
            }
        },
        'states': {
            state.name: state.to_dict() for state in self.__id_to_state
        },
        'transitions': {
            from_state: [{
                "on": act.to_dict(),
                "goto": to_state
            } for to_state, action_list in to_states.items()
                for act in action_list if not act.is_teleport()
            ] for from_state, to_states in self.transitions.items() if len(to_states) > 0
        },
        'teleports': {
            from_state: [{
                "on": act.to_dict(),
                "goto": to_state
            } for to_state, action_list in to_states.items()
                for act in action_list
            ] for from_state, to_states in teleport_transitions.items() if len(to_states) > 0
        }
    }

Returns the machine as a dictionary in the JSON format. Messages are encoded as ASCII with the other characters written as HTML entities. Arguments, messages and timing values of actions and states are written after the replacement of the wildcards. The welcome message in machine.msg keeps its wildcards. Teleports present from every state other than their destination are grouped under all.

save

save(filename: str, only_if_changed: AgentBasics | None = None) -> bool
Source code in unaiverse/hsm/hsm.py
def save(self, filename: str, only_if_changed: "AgentBasics | None" = None) -> bool:
    """Saves the state machine's current configuration to a JSON file. It can optionally check if the configuration
    has changed before saving to avoid redundant file writes.

    Args:
        filename: The path to the file to save to.
        only_if_changed: An optional object to compare against for changes. If a change is not detected, the file
            is not written.

    Returns:
        True if the file was written, False otherwise.
    """
    if only_if_changed is not None and os.path.exists(filename):
        try:
            existing = HybridStateMachine(agent=only_if_changed).load(filename)
            if str(existing) == str(self):
                return False
        except Exception as e:  # If load fails, we assume it changed
            log.error(f"Error while reloading the exising machine from {filename}, "
                      f"assuming it changed: {e}")

    with open(filename, 'w', encoding='utf-8') as file:
        file.write(str(self))
    return True

Writes to_dict() as indented JSON in UTF-8 to filename. Values that are not basic JSON types become the string "_non_basic_type_removed_". With only_if_changed=agent the method first loads an existing file into a new machine of that agent and compares it with this one. When the two are equal it returns False and writes nothing. A file that fails to load is logged and treated as changed. The method returns True when it wrote the file. A world calls it at start for each role and thereby rewrites the files of its folder in the normalized form.

load

load(filename_or_hsm_as_string: str | TextIOWrapper | IO[str]) -> HybridStateMachine
Source code in unaiverse/hsm/hsm.py
def load(self, filename_or_hsm_as_string: str | io.TextIOWrapper | IO[str]) -> 'HybridStateMachine':
    """Loads a state machine's configuration from a JSON file or a JSON string. It reconstructs the states,
    actions, and transitions from the serialized data. This method is critical for persistence and for loading
    pre-defined state machine models.

    Args:
        filename_or_hsm_as_string: The path to the JSON file or a JSON string representation of the state machine.

    Returns:
        The loaded `HybridStateMachine` object (self).
    """

    # Loading the whole file
    if (isinstance(filename_or_hsm_as_string, Traversable) or
            isinstance(filename_or_hsm_as_string, io.TextIOWrapper)):

        # Safe way to load when this file is packed in a pip package
        hsm_data = json.load(filename_or_hsm_as_string)  # noqa
    else:

        # Ordinary case
        if os.path.exists(filename_or_hsm_as_string) and os.path.isfile(filename_or_hsm_as_string):    # noqa
            with open(filename_or_hsm_as_string, 'r', encoding="utf-8") as file:    # noqa
                hsm_data = json.load(file)
        else:

            # Assuming it is a string
            hsm_data = json.loads(filename_or_hsm_as_string)  # noqa

    # Backward compatibility
    if "machine" not in hsm_data:
        return self.load_backward_compat(hsm_data)

    # Getting state info
    try:
        self.initial_state = hsm_data['machine']['initial_state']
        self.state = self.initial_state
        self.prev_state = None
        self.limbo_state = None
        self.set_welcome_message(hsm_data['machine'].get('msg', None))
        self.set_role(hsm_data['machine']['role'])  # Do it AFTER having set the welcome message
        self.show_blocking_states = (
            hsm_data['machine']['options'].get('highlight_blocking_states_in_messages', False))
        self.show_action_completion = (
            hsm_data['machine']['options'].get('show_action_ticks_after_messages', False))
        self.show_action_request_info = (
            hsm_data['machine']['options'].get('show_action_request_after_messages', False))
    except Exception as e:
        log.critical(f"Invalid JSON data format when loading the state machine [{e}]")

    self.states = {}
    self.transitions = {}

    # Getting states
    if 'states' not in hsm_data:
        log.critical(f"Invalid JSON data format when loading the state machine (missing state list)")

    for state, state_action in hsm_data['states'].items():
        act_name = state_action.get("action", None)
        act_args = state_action.get("action_kwargs", {})
        blocking = state_action.get("blocking", True)
        msg = state_action.get("msg", None)
        waiting_time = 0.
        for k in Custom.TIME_TO_WAIT_BEFORE_ACTING_ARG_NAMES:
            if k in state_action:
                waiting_time = state_action[k]
                break

        self.add_state(state, action=act_name, args=act_args,
                       waiting_time=waiting_time, blocking=blocking, msg=msg)

    # Getting ordinary transitions (before teleports, to ensure higher priority)
    if 'transitions' in hsm_data:
        for from_state, list_of_to_state_dicts in hsm_data['transitions'].items():
            for to_state_dict in list_of_to_state_dicts:
                to_state = to_state_dict["goto"]
                action_dict = to_state_dict["on"]

                act_name = action_dict["action"]
                act_args = action_dict.get("action_kwargs", {})
                msg = action_dict.get("msg", None)
                act_ready = action_dict.get("ready", True)
                high_priority = action_dict.get("high_priority", False)
                total_time = 0.
                for k in Custom.SECONDS_ARG_NAMES:
                    if k in action_dict:
                        total_time = action_dict[k]
                        break
                timeout = 0.
                for k in Custom.TIMEOUT_ARG_NAMES:
                    if k in action_dict:
                        timeout = action_dict[k]
                        break
                delay = 0.
                for k in Custom.DELAY_ARG_NAMES:
                    if k in action_dict:
                        delay = action_dict[k]
                        break

                self.add_transit(from_state, to_state,
                                 action=act_name, args=act_args, ready=act_ready, msg=msg,
                                 avoid_changing_ready="ready" in action_dict, total_time=total_time,
                                 high_priority=high_priority,
                                 timeout=timeout, delay=delay)

    # Getting teleports (do it after getting ordinary transitions, so teleports will have lower priority)
    if 'teleports' in hsm_data:

        # Replicating the "all" teleport over all source states
        if Custom.ALL_STATES_NAME in hsm_data['teleports']:
            list_of_to_state_dicts = hsm_data['teleports'][Custom.ALL_STATES_NAME]

            for to_state_dict in list_of_to_state_dicts:
                to_state = to_state_dict["goto"]
                action_dict = to_state_dict["on"]

                act_name = action_dict["action"]
                act_args = action_dict.get("action_kwargs", {})
                msg = action_dict.get("msg", None)
                act_ready = action_dict.get("ready", True)
                high_priority = action_dict.get("high_priority", False)
                total_time = 0.
                for k in Custom.SECONDS_ARG_NAMES:
                    if k in action_dict:
                        total_time = action_dict[k]
                        break
                timeout = 0.
                for k in Custom.TIMEOUT_ARG_NAMES:
                    if k in action_dict:
                        timeout = action_dict[k]
                        break
                delay = 0.
                for k in Custom.DELAY_ARG_NAMES:
                    if k in action_dict:
                        delay = action_dict[k]
                        break

                # Looping over all states
                for from_state_obj in self.__id_to_state:
                    from_state = from_state_obj.name

                    # Skipping the destination state
                    if from_state == to_state:
                        continue

                    self.add_transit(from_state, to_state,
                                     action=act_name, args=act_args, ready=act_ready, msg=msg,
                                     avoid_changing_ready="ready" in action_dict, teleport=True,
                                     high_priority=high_priority,
                                     total_time=total_time, timeout=timeout, delay=delay)

        # Handling all the ordinary teleports
        for from_state, list_of_to_state_dicts in hsm_data['teleports'].items():

            # Skipping "all"-like teleport (already handled)
            if from_state == Custom.ALL_STATES_NAME:
                continue

            for to_state_dict in list_of_to_state_dicts:
                to_state = to_state_dict["goto"]
                action_dict = to_state_dict["on"]

                act_name = action_dict["action"]
                act_args = action_dict.get("action_kwargs", {})
                msg = action_dict.get("msg", None)
                act_ready = action_dict.get("ready", True)
                high_priority = action_dict.get("high_priority", False)
                total_time = 0.
                for k in Custom.SECONDS_ARG_NAMES:
                    if k in action_dict:
                        total_time = action_dict[k]
                        break
                timeout = 0.
                for k in Custom.TIMEOUT_ARG_NAMES:
                    if k in action_dict:
                        timeout = action_dict[k]
                        break
                delay = 0.
                for k in Custom.DELAY_ARG_NAMES:
                    if k in action_dict:
                        delay = action_dict[k]
                        break

                self.add_transit(from_state, to_state,
                                 action=act_name, args=act_args, ready=act_ready, msg=msg,
                                 avoid_changing_ready="ready" in action_dict, teleport=True,
                                 high_priority=high_priority,
                                 total_time=total_time, timeout=timeout, delay=delay)

    return self

Reads a behavior into this machine and returns the machine itself. The usual call is HybridStateMachine(agent).load(path). The argument filename_or_hsm_as_string is one of (1) a path to an existing file, (2) a text file opened with open() or a resource from importlib.resources and (3) a string holding the JSON text. Any string that is not an existing path is parsed as JSON and a wrong path therefore raises json.JSONDecodeError. An io.StringIO is not accepted and raises TypeError. A dictionary without the key machine goes to load_backward_compat().

The method replaces states and transitions and keeps the internal lists of states and actions. It must therefore be called on a new machine. Errors in machine and a missing states raise GenException. The errors of the single transitions are those of add_state() and add_transit().

load_backward_compat

load_backward_compat(hsm_data: dict) -> HybridStateMachine
Source code in unaiverse/hsm/hsm.py
def load_backward_compat(self, hsm_data: dict) -> 'HybridStateMachine':
    """Loads a state machine's configuration from a JSON file or a JSON string. It reconstructs the states,
    actions, and transitions from the serialized data. This method is critical for persistence and for loading
    pre-defined state machine models.

    Args:
        hsm_data: The dict with an HSM loaded from a JSON file.

    Returns:
        The loaded `HybridStateMachine` object (self).
    """

    # Getting state info
    self.initial_state = hsm_data['initial_state']
    self.state = hsm_data['state']
    self.prev_state = hsm_data['prev_state']
    self.limbo_state = hsm_data['limbo_state']
    self.set_welcome_message(hsm_data.get('welcome_msg', None))
    self.set_role(hsm_data.get('role', 'unknown'))  # Do it AFTER set_welcome_message
    self.show_blocking_states = hsm_data.get('highlight_blocking_states_in_messages', False)
    self.show_action_completion = hsm_data.get('show_action_ticks_after_messages', False)
    self.show_action_request_info = hsm_data.get('show_action_request_after_messages', False)

    # Getting states
    self.states = {}
    if 'state_actions' in hsm_data:
        for state, state_action_list in hsm_data['state_actions'].items():
            if len(state_action_list) == 3:  # Backward compatibility
                act_name, act_args, state_id = state_action_list
                waiting_time = 0.
                blocking = True
                msg = None
            elif len(state_action_list) == 4:  # Backward compatibility
                act_name, act_args, state_id, waiting_time_or_blocking = state_action_list
                if isinstance(waiting_time_or_blocking, bool):
                    waiting_time = 0.
                    blocking = waiting_time_or_blocking
                else:
                    waiting_time = waiting_time_or_blocking
                    blocking = True
                msg = None
            elif len(state_action_list) == 5:  # Backward compatibility
                act_name, act_args, state_id, blocking, waiting_time = state_action_list
                msg = None
            else:
                act_name, act_args, state_id, blocking, waiting_time, msg = state_action_list

            # Recall that state_id can be set to -1 in the original file, meaning "automatically set the state_id"
            self.add_state(state, action=act_name, args=act_args,
                           state_id=state_id if state_id >= 0 else None,
                           waiting_time=waiting_time, blocking=blocking, msg=msg)

    # Getting transitions
    self.transitions = {}
    for from_state, to_states in hsm_data['transitions'].items():
        for to_state, action_list in to_states.items():
            for action_list_tuple in action_list:
                if len(action_list_tuple) == 4:
                    act_name, act_args, act_ready, act_id = action_list_tuple
                    msg = None
                else:
                    act_name, act_args, act_ready, act_id, msg = action_list_tuple

                # Recall that act_id can be set to -1 in the original file, meaning "automatically set the act_id"
                self.add_transit(from_state, to_state,
                                 action=act_name, args=act_args, ready=act_ready,
                                 act_id=act_id if act_id >= 0 else None, msg=msg,
                                 avoid_changing_ready=True)
    return self

Reads a dictionary in the format used before the key machine existed and returns the machine. The format has the top-level keys initial_state, state, prev_state and limbo_state, an optional welcome_msg, an optional role (default "unknown") and the three display options. state_actions holds lists of 3 to 6 elements ([action, args, id, blocking, waiting_time, msg] in the longest form) and transitions has the form {from: {to: [[action, args, ready, id, msg], ...]}}. An id of -1 means an automatic id. load() is the only caller.

to_graphviz

to_graphviz() -> Digraph
Source code in unaiverse/hsm/hsm.py
def to_graphviz(self) -> graphviz.Digraph:
    """Generates a Graphviz `Digraph` object representing the state machine's structure. This method visualizes
    states as nodes and transitions as edges. It includes details such as node shapes (diamond for initial state,
    oval for others), styles (filled for blocking states), and labels for both states and transitions. The labels
    for actions include their names and arguments, formatted to wrap lines for readability.

    Returns:
        A `graphviz.Digraph` object ready for rendering.
    """
    graph = graphviz.Digraph()
    graph.attr('node', fontsize='8')
    for state, state_obj in self.states.items():
        action = state_obj.action
        if action is not None:
            s = "("
            for i, (k, v) in enumerate(action.args.items()):
                s += str(k) + "=" + (str(v) if not isinstance(v, str) else ("'" + v + "'"))
                if i < len(action.args) - 1:
                    s += ", "
            s += ")"
            label = action.name + s
            if len(label) > 40:
                tokens = label.split(" ")
                z = ""
                i = 0
                done = False
                while i < len(tokens):
                    z += (" " if i > 0 else "") + tokens[i]
                    if not done and i < (len(tokens) - 1) and len(z + tokens[i + 1]) > 40:
                        z += "\n    "
                        done = True
                    i += 1
                label = z
            suffix = "\n" + label
        else:
            suffix = ""
        if state == self.initial_state:
            graph.attr('node', shape='diamond')
        else:
            graph.attr('node', shape='oval')
        if self.states[state].blocking:
            graph.attr('node', style='filled')
        else:
            graph.attr('node', style='solid')
        graph.node(state, state + suffix, _attributes={'id': "node" + str(state_obj.id)})

    for from_state, to_states in self.transitions.items():
        j = 1
        for to_state, action_list in to_states.items():
            loop_groups = {}  # (style, color) -> [merged label, id of first action]
            for action in action_list:
                args = action.args
                s = "("
                for i, (k, v) in enumerate(args.items()):
                    s += str(k) + "=" + (str(v) if not isinstance(v, str) else ("'" + str(v) + "'"))
                    if i < len(args) - 1:
                        s += ", "
                s += ")"

                special_args = {}
                if isinstance(action.get_total_time(), str) or action.get_total_time() > 0:
                    total_time = action.get_total_time()
                    special_args[Custom.SECONDS_ARG_NAMES[0]] = total_time
                if isinstance(action.get_timeout(), str) or action.get_timeout() > 0.:
                    timeout = action.get_timeout()
                    special_args[Custom.TIMEOUT_ARG_NAMES[0]] = timeout
                if isinstance(action.get_delay(), str) or action.get_delay() > 0.:
                    delay = action.get_delay()
                    special_args[Custom.DELAY_ARG_NAMES[0]] = delay

                if len(special_args) > 0:
                    s += "\n["
                    for i, (k, v) in enumerate(special_args.items()):
                        s += str(k) + "=" + (str(v) if not isinstance(v, str) else ("'" + str(v) + "'"))
                        if i < len(special_args) - 1:
                            s += ", "
                    s += "]"

                label = str(j) + "." + action.name + s
                j += 1
                if len(label) > 40:
                    tokens = label.split(" ")
                    z = ""
                    i = 0
                    done = False
                    while i < len(tokens):
                        z += (" " if i > 0 else "") + tokens[i]
                        if not done and i < (len(tokens) - 1) and len(z + tokens[i + 1]) > 40:
                            z += "\n"
                            done = True
                        i += 1
                    label = z
                edge_style = 'dashed' if not action.is_ready() else 'solid'
                edge_color = "#00000050" if action.is_teleport() else "#000000"

                if from_state == to_state and len(action_list) > 1:
                    group = loop_groups.setdefault((edge_style, edge_color), ["", action.id])
                    group[0] += ("\n" if group[0] else "") + label
                else:
                    graph.edge(from_state, to_state, label=" " + label + " ", fontsize='8',
                               style=edge_style, color=edge_color, fontcolor=edge_color,
                               _attributes={'id': "edge" + str(action.id)})

            for (edge_style, edge_color), (label, first_id) in loop_groups.items():
                graph.edge(from_state, to_state, label=" " + label + " ", fontsize='8',
                           style=edge_style, color=edge_color, fontcolor=edge_color,
                           _attributes={'id': "edge" + str(first_id)})
    return graph

Returns a graphviz.Digraph of the machine where the initial state is a diamond, the other states are ovals and blocking states are filled. Each edge carries the label n.action(args) with the non-zero timing fields in brackets. An edge is dashed when its action is not ready and faded when it is a teleport. Self-loops of one state with the same style are merged into one edge. Nodes and edges carry the ids node<state id> and edge<action id>.

save_pdf

save_pdf(filename: str) -> bool
Source code in unaiverse/hsm/hsm.py
def save_pdf(self, filename: str) -> bool:
    """Saves the state machine's Graphviz representation as a PDF file. It calls `to_graphviz()` to create the
    graph and then uses the Graphviz library's `render` method to generate the PDF.

    Args:
        filename: The path and name of the PDF file to save.

    Returns:
        True if the file was successfully saved, False otherwise.
    """
    if filename.lower().endswith(".pdf"):
        filename = filename[0:-4]

    try:
        self.to_graphviz().render(filename, format='pdf', cleanup=True)
        return True
    except Exception as e:
        log.error(f"Error while saving to PDF {e}")
        return False

Renders to_graphviz() to filename as a PDF. Graphviz appends the extension by itself and the method removes a trailing .pdf from the name for this reason. The Graphviz program must be installed. The method returns True on success and False after logging the error. A world calls it for each role and stores the drawings in <world_folder>/pdf/.

Policy API

set_policy

set_policy(policy_fcn: Callable[[int, Interaction | None, list[Action], dict], tuple[int, Interaction | None]] | None) -> None
Source code in unaiverse/hsm/hsm.py
def set_policy(self, policy_fcn: Callable[[int,
                                           Interaction | None,
                                           list[Action], dict], tuple[int, Interaction | None]] | None) -> None:
    """Sets the policy to be used in selecting what action to perform in the current state.

    Args:
        policy_fcn: A function that takes a list of `Action` objects that are candidates for execution, and returns
            the index of the selected action and an ActionRequest object with the action-requester details (object,
            arguments, time, and UUID), or -1 and None if no action is selected.
    """
    self.policy = policy_fcn

Replaces the policy with policy_fcn and returns None. The machine calls the policy with one argument (the list of feasible actions) and expects (index, interaction) as described in Policies. The type hint of policy_fcn in the signature declares four arguments and does not match this call. agent.set_policy() is the method that changes the policy of an agent.

set_policy_filter

set_policy_filter(filter_fcn: Callable[[int, Interaction | None, list[Action], dict], tuple[int, Interaction | None]] | None, filter_fcn_opts: dict) -> None
Source code in unaiverse/hsm/hsm.py
def set_policy_filter(self, filter_fcn: Callable[
    [int, Interaction | None, list[Action], dict], tuple[int, Interaction | None]] | None,
                      filter_fcn_opts: dict) -> None:
    """Sets the filter function that will overload the decision of the policy.

    Args:
        filter_fcn: A function that takes the decision of the policy, a list of `Action` objects
            that are candidates for execution, and a customizable dict of options, and returns the index of the
            selected action and an ActionRequest with the requested details (requests, arguments, time, and UUID),
            or -1 and None if no action is selected.
        filter_fcn_opts: A reference to the dictionary of custom options that will be passed to the filter function.
    """
    self.policy_filter = filter_fcn
    self.policy_filter_opts = filter_fcn_opts
    self.policy_filter_opts.clear()  # It is cleared on set, it will be filled up later

Installs filter_fcn as the policy filter and filter_fcn_opts as its options dictionary. The method empties filter_fcn_opts in place before returning. The value None removes the filter. agent.set_policy_filter() is the method that changes the filter of an agent because it also fills opts. Returns None.

set_actionable

set_actionable(obj: AgentBasics) -> None
Source code in unaiverse/hsm/hsm.py
def set_actionable(self, obj: "AgentBasics") -> None:
    """Sets the object on which the state machine's actions will be performed. This allows the same state machine
    logic to be applied to different objects. It updates the `agent` reference for all states and actions
    within the machine.

    Args:
        obj: The object instance to be set as the new `agent`.
    """
    if obj is None:
        log.critical("Unexpected None for the agent HSM actionable")
        return  # This is dead code, since log.critical raises a GenException, but I keep it here to remember

    self.agent = obj

    for state_obj in self.states.values():
        if state_obj.action is not None:
            state_obj.action.agent = obj

    for action_obj in self.__id_to_action:
        if action_obj is not None:
            action_obj.agent = obj

Makes obj the owner of every action of the machine and returns None. The constructor calls it and the value None raises GenException. The actions keep the methods resolved on the previous owner. This call therefore changes only the attribute agent of the machine and of its actions.