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.
fromunaiverse.agentimportAgent,actionfromunaiverse.hsmimportHybridStateMachineclassSensor(Agent):@actionasyncdefcalibrate(self,offset:float=0.0)->bool:self.offset=offsetreturnTrue@actionasyncdefmeasure(self,interaction=None)->bool:returnawaitself.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").
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.
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.
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.
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.
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.
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.
When the machine is in its initial state and has a welcome message, the message is printed and then removed from the machine.
act_states() runs the action of the current state when the state has one.
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.
The policy picks one action and optionally one of its pending interactions. The policy filter can change or veto the choice.
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.
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.
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__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 actionself.initial_state=None# Initial state of the machineself.prev_state=None# Previous stateself.limbo_state=None# When an action takes more than a step to complete, we are in "limbo"self.state:str|None=None# Current stateself.role:str|None=None# Role of the agent in the state machine (e.g., teacher, student, etc.)self.enabled:bool=Trueself.states:dict[str,State]={}# State name to State object# Actions (transitions) are handled as Action objects in-between state stringsself.transitions:dict[str,dict[str,list[Action]]]={}# Pair-of-states to the actions between themself.agent:"AgentBasics"=agent# The object on whose methods are actions that the machine callsself.wildcards:dict[str,str|float|int|list[str]]=wildcards \
ifwildcardsisnotNoneelse{}# From a wildcards string to a specific value (used in action arguments)self.policy=policyifpolicyisnotNoneelseself.__policy_first_requested_or_first_readyself.policy_filter:Callable|None=Noneself.policy_filter_opts={}self.welcome_msg=Noneself.welcome_msg_with_wildcards=Noneself.show_blocking_states=Falseself.show_action_completion=Falseself.show_action_request_info=False# Running dataself.__action:Action|None=None# Action that is being executed (could take more than a step to complete)self.__last_completed_action:Action|None=Noneself.__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 objectself.__id_to_action:list[Action]=[]# Map from action ID to Action objectself.__state_changed=False# Internal flagself.__id_to_original_state_msg:list[tuple[str|None,str|None]]=[]self.__id_to_original_action_msg:list[str|None]=[]# Forcing default wildcardsself.add_wildcards(Custom.DEFAULT_WILDCARDS)# Applying to the welcome message, state, actions, if neededself.apply_wildcards()# Forcing output functionself.__debug_messages_active=Falseself.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.
defadd_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. """ifargsisNone:args={}sta_obj=Noneifstate_idisNone:ifstatenotinself.states:state_id=len(self.__id_to_state)else:sta_obj=self.states[state]state_id=sta_obj.idifactionisNone:act=sta_obj.actionifsta_objisnotNoneelseNoneelse:assertself.agentisnotNoneact=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)ifwaiting_timeisNone:waiting_time=sta_obj.waiting_timeifsta_objisnotNoneelse0.# Default waiting timeifblockingisNone:blocking=sta_obj.blockingifsta_objisnotNoneelseTrue# Default blockingifmsgisNone:msg=sta_obj.msg_with_wildcardsifsta_objisnotNoneelseNonesta=State(name=state,idx=state_id,action=act,waiting_time=waiting_time,blocking=blocking,msg=msg)sta.set_wildcards(self.wildcards)ifstatenotinself.states:self.__id_to_state.append(sta)else:self.__id_to_state[state_id]=staself.states[state]=staiflen(self.__id_to_state)==1andself.stateisNone: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
defadd_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 namesiffrom_state==Custom.ALL_STATES_NAME:forfrom_state_objinself.__id_to_state:# Skipping the destination state, mirroring the load-time 'all' expansioniffrom_state_obj.name==to_state:continue# Adding a transition to the dest stateself.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 HSMifto_state.lower().endswith(".json"):ifnotos.path.exists(to_state):raiseFileNotFoundError(f"Cannot find {to_state}")file_name=to_statehsm=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)forstateinhsm_states:renamed_state=statei=1whilerenamed_stateinself.statesor(i>1andrenamed_stateinhsm.states):renamed_state=state+"."+str(i)i+=1ifhsm.initial_state==state:hsm.initial_state=renamed_stateifhsm.prev_state==state:hsm.prev_state=renamed_stateifhsm.state==state:hsm.state=renamed_stateifhsm.limbo_state==state:hsm.limbo_state=renamed_statehsm.states[renamed_state]=hsm.states[state]ifrenamed_state!=state:delhsm.states[state]hsm.transitions[renamed_state]=hsm.transitions[state]ifrenamed_state!=state:delhsm.transitions[state]forto_statesinhsm.transitions.values():ifstateinto_states:to_states[renamed_state]=to_states[state]ifrenamed_state!=state:delto_states[state]# Savinginitial_state_was_set=self.initial_stateisnotNonestate_was_set=self.stateisnotNone# Include actions/states from another HSMself.include(hsm)# Adding a transition to the initial state of the given HSMself.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)# Restoringself.initial_state=from_stateifnotinitial_state_was_setelseself.initial_stateself.state=from_stateifnotstate_was_setelseself.statereturn# Adding a new transitioniffrom_statenotinself.transitions:iffrom_statenotinself.states:self.add_state(from_state,action=None)self.transitions[from_state]={}ifto_statenotinself.transitions:ifto_statenotinself.states:self.add_state(to_state,action=None)self.transitions[to_state]={}ifargsisNone:args={}ifact_idisNone:act_id=len(self.__id_to_action)# Clearingifto_statenotinself.transitions[from_state]:self.transitions[from_state][to_state]=[]# Checkingexisting_action_list=self.transitions[from_state][to_state]forexisting_actioninexisting_action_list:ifexisting_action.same_as(name=action,args=args):raiseValueError(f"Repeated transition from {from_state} to {to_state}: "f"{existing_action.to_list()}")# Adding the new actionnew_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).
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.
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:
definclude(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 wildcardsself.add_wildcards(hsm.get_wildcards())# Adding states before adding transitions, so that we also add inner state actions, if anyfor_stateinhsm.states.values():self.add_state(state=_state.name,action=_state.action.nameif_state.actionisnotNoneelseNone,waiting_time=_state.waiting_time,args=_state.action.argsif_state.actionisnotNoneelseNone,state_id=None,blocking=_state.blocking,msg=_state.msg_with_wildcards,msg_action=_state.action.msg_with_wildcardsif_state.actionisnotNoneelseNone)# Copy all the transitions of the HSMfor_from_state,_to_statesinhsm.transitions.items():for_to_state,_action_listin_to_states.items():for_actionin_action_list:total_time=0.timeout=0.delay=0.ifisinstance(_action.get_total_time(),str)or_action.get_total_time()>0:total_time=_action.get_total_time()ifisinstance(_action.get_timeout(),str)or_action.get_timeout()>0.:timeout=_action.get_timeout()ifisinstance(_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)ifmake_a_copy:self.state=hsm.stateself.prev_state=hsm.prev_stateself.initial_state=hsm.initial_stateself.limbo_state=hsm.limbo_stateself.set_welcome_message(hsm.welcome_msg_with_wildcards)self.show_blocking_states=hsm.show_blocking_statesself.show_action_completion=hsm.show_action_completionself.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.
defset_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=roleself.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.
defset_welcome_message(self,msg:str|None)->None:"""Sets a message that will be printed only once when the initial state is reached."""ifmsgisnotNone:self.welcome_msg=html.unescape(msg)self.welcome_msg_with_wildcards=self.welcome_msgelse:self.welcome_msg=Noneself.welcome_msg_with_wildcards=None
Stores the welcome message msg after decoding its HTML entities (👋 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.
defget_wildcards(self)->dict:"""Retrieves the dictionary of wildcards currently used by the state machine. Returns: A dictionary of the wildcards. """returnself.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().
defset_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=wildcardsifwildcardsisnotNoneelse{}# Saving wildcard dictionary, completely replacing the previous oneself.wildcards=wildcards# Propagating the reference to the new dictionary to actions and states.foractioninself.__id_to_action:action.set_wildcards(self.wildcards)forstateinself.__id_to_state:state.set_wildcards(self.wildcards)ifapply: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.
defadd_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 dictionaryself.wildcards.update(wildcards)ifapply: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.
defupdate_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). """ifwildcard_keynotinself.wildcards:log.error(f"{wildcard_key} is not a valid wildcard")else:self.wildcards[wildcard_key]=wildcard_valueifapply: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.
defapply_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.foractioninself.__id_to_action:action.apply_wildcards()forstateinself.__id_to_state:state.apply_wildcards()# If there is a welcome message that includes wildcards...ifself.welcome_msgisnotNone:self.welcome_msg=self.welcome_msg_with_wildcards# Restore before updatingforwildcard_from,wildcard_toinself.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.
asyncdefact(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 reachedchanged_state=Falsestarting_state=self.statewhileTrue:ifself.welcome_msgisnotNoneandself.stateisnotNoneandself.state==self.initial_state:log.user(self.welcome_msg)self.set_welcome_message(None)awaitself.act_states()ret=awaitself.act_transitions(self.must_wait())ifself.state!=starting_state:# Value of self.state might change while act_transitions runschanged_state=Trueifret!=0or(self.stateisnotNoneandself.states[self.state].blocking):breakreturnchanged_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.
asyncdefact_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). """ifnotself.enabled:returnifself.stateisnotNone:# When in the middle of an action, the state is Nonesawaitself.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.
asyncdefact_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. """ifnotself.enabled:return-1# Collecting list of feasible actions, wait flags, etc. (from the current state)ifself.__cur_feasible_actions_statusisNone:ifself.stateisNone:return-1actions_list=[]to_state_list:list[str]=[]attempts_to_serve_an_interaction_list=[]forto_state,action_listinself.transitions[self.state].items():fori,actioninenumerate(action_list):# Checking is_ready will check if streams are ready and if the interaction was completed meanwhileif(action.is_ready(consider_interactions=True,delay_starting_time=self.states[self.state].starting_time)and(notonly_the_ones_with_interactionsorlen(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)iflen(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)assertlen(actions_list)==0orisinstance(self.__cur_feasible_actions_status,dict)# Using the selected policy to decide what action to applywhilelen(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)ifself.__actionisNone:log.statem(f"List of actions to choose from:\n "+"\n ".join([a.to_code_str().replace("\n","\n ")forainactions_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 appliedself.__cur_feasible_actions_status=Noneself.__state_changed=Falsereturn-1# Early stopelse:if_interactionisnotNone: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 filterifself.policy_filterisnotNone: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!=_interactionand_interactions_fisnotNone:_interactions_f=self.agent.im.get_interaction(uuid=_interactions_f.uuid)exceptExceptionase:log.error(f"Skipping policy filter due to exception: {e}",state=self.get_state_name())_idx_f=_idx_interactions_f=_interactionif_idx_f!=_idxor_interactions_f!=_interaction:if_idx_f<0:log.statem(f"Filter selected no actions among {[a.nameforainactions_list]}")# No actions were applied# self.__cur_feasible_actions_status = None# self.__state_changed = False# return -1 # Early stopskip_action_due_to_filter=Trueelse:_idx=_idx_f_interaction=_interactions_fif_interactionisnotNone: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 actionself.limbo_state=self.stateself.state=Noneself.__action=actions_list[_idx]assertself.__actionisnotNone# Forcing system interaction if no external interactions were selectedif_interactionisNone:_interaction=self.__action.system_interaction_interaction.reset_state()# Resettingassertself.__cur_feasible_actions_statusisnotNoneself.__cur_feasible_actions_status['selected_idx']=_idxself.__cur_feasible_actions_status['selected_interaction']=_interaction# Referencesassertself.__cur_feasible_actions_statusisnotNoneaction=self.__actionidx=self.__cur_feasible_actions_status['selected_idx']interaction:Interaction=self.__cur_feasible_actions_status['selected_interaction']assertinteractionisnotNone# 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 streamsifself.agent.im.currentisNoneorself.agent.im.current!=interaction:self.agent.im.set_current(interaction)log.statem(f">>> ACTION {action.name}...",state=self.get_state_name(True))iflen(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=(awaitaction(interaction=interaction))ifnotskip_action_due_to_filterelse2# noqaifstatus==0:log.statem(f"+++ ACTION {action.name} correctly completed",state=self.get_state_name(True))elifstatus==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))ifaction.msgisnotNoneandself.show_action_completion:log.user(Custom.ACTION_TICKS_PER_STATUS[status])# Post-call operationsifstatus==0:# Done# State transitionself.prev_state=self.limbo_stateidx:intself.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 stateawaitself.agent.im.complete_current(self.state,CompletionReason.OK)# Update statusself.__state_changed=self.state!=self.prev_state# Checking if we are on a self-loop or notself.__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")ifself.__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 stateaction.reset_msg_printing()ifself.__state_changed:self.__reset_msg_printing(self.prev_state)interaction.reset_state()self.__action=None# Clearingself.__cur_feasible_actions_status=Nonereturn0# Transition done, no need to check other actions!elifstatus==1:# Try again the same action (either a new step or an already done-and-failed one)# Update statusself.__state_changed=False# if self.prev_state is not None:# self.states[self.prev_state].reset() # Reset starting timereturn1# Transition not-done: no need to check other actions, the current one will be run againelifstatus==2:# Move to the next action (or to the next request of the same action)# Clearing requestassertself.__actionisnotNoneself.__action.interactions.move_interaction_to_back(interaction)# Rotating to avoid starvationattempts_to_serve_an_interaction_list[idx]+=1# Back to the original stateself.state=self.limbo_stateself.limbo_state=None# Purging action from the current listattempts_to_serve_an_interaction_list:list[int]ifattempts_to_serve_an_interaction_list[idx]>=len(self.__action.get_list_of_interactions()):delactions_list[idx]delto_state_list[idx]delattempts_to_serve_an_interaction_list[idx]# Update statusself.__state_changed=Falseinteraction.reset_state()self.agent.im.set_current_as_paused()self.__action=None# Clearingcontinue# Move to the next actionelse:raiseValueError("Unexpected status: "+str(status))# No actions were appliedself.__cur_feasible_actions_status=Noneself.__state_changed=Falsereturn-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.
asyncdefact_ghost_transition(self,to_state:str)->int:# Forcing to go back to current state if in the middle of a multistep actionfrom_state=self.stateiffrom_stateisNone:from_state=self.limbo_stateself.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 stateoriginal_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=awaitself.act_transitions()# Restoring original transitionsself.transitions[from_state]=original_transitionsreturnret
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.
defmust_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. """ifself.stateisnotNone:returnself.states[self.state].must_wait()else:returnFalse
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().
defenable(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.
defis_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. """returnself.enabled
defget_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. """returnself.__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.
defrequest_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 dataaction_name=interaction.action_nameargs=interaction.action_kwargsifaction_nameisNone:log.error(f"Requested an action with no name!")returnFalse# If state is not provided, the current state is assumedfrom_state=interaction.from_stateiffrom_stateisNone:# If the request arrives in the middle of a multistep action, we need to check limbo statefrom_state=self.stateifself.stateisnotNoneelseself.limbo_stateiffrom_statenotinself.transitions:log.error(f"Request not accepted: not valid source state ({from_state})",state=self.get_state_name())returnFalse# If the destination state is not provided, all the possible destination from the current state are consideredto_state=interaction.to_stateifto_stateisnotNoneandto_statenotinself.transitions[from_state]:log.error(f"Request not accepted: not valid destination state ({to_state})",state=self.get_state_name())returnFalseto_states=self.transitions[from_state].keys()ifto_stateisNoneelse[to_state]forto_stateinto_states:action_list=self.transitions[from_state][to_state]fori,actioninenumerate(action_list):ifaction.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 suggestionifaction.add_interaction(interaction):returnTrueelse:log.error("Requested action does not allow interactions")returnFalse# If the action does not support interactions# If the action was not foundlog.error(f"Requested action ({action_name}) not found "f"(from_state={from_state}, cur_state={self.get_state_name()})",state=self.get_state_name())returnFalse
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.
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.
defwait_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. """forstate,to_statesinself.transitions.items():forto_state,action_listinto_states.items():fori,actioninenumerate(action_list):ifaction.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.
defwait_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. """forstate,to_statesinself.transitions.items():forto_state,action_listinto_states.items():fori,actioninenumerate(action_list):ifarg_nameinaction.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.
defget_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. """ifnotconsider_limbo:returnself.stateelse:ifself.stateisNoneandself.limbo_stateisnotNone:returnself.limbo_stateelse:returnself.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.
defget_state(self)->'State | None':"""Retrieves the current `State` object of the state machine. Returns: A `State` object or `None`. """returnself.states[self.state]ifself.stateisnotNoneelseNone
Returns the State object of the current state. The result is None while an action runs.
defget_states(self)->list:"""Returns an iterable of all state names defined in the state machine. Returns: An iterable of state names. """return[s.nameforsinself.__id_to_state]
Returns the list of the state names in the order in which they were added.
defget_all_actions(self)->list['Action']:"""Retrieves the list of all `Action` objects. Returns: List of `Action` objects. """returnself.__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.
defget_action(self)->'Action | None':"""Retrieves the `Action` object that is currently being executed. Returns: An `Action` object or `None`. """returnself.__action
Returns the running Action or None when no action runs.
defget_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. """returnself.__action.nameifself.__actionisnotNoneelseNone
Returns the name of the running action or None when no action runs. The agent records it in its statistics as action.
defget_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. """returnself.__last_completed_action.nameifself.__last_completed_actionisnotNoneelseNone
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.
defget_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. """assertself.__actionisNoneorisinstance(self.__cur_feasible_actions_status,dict)ifself.__actionisNone:return-1else:assertisinstance(self.__cur_feasible_actions_status,dict)returnself.__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().
defis_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. """returnself.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.
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.
defset_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. """ifstateinself.transitionsorstateinself.states:self.limbo_state=Noneself.prev_state=self.stateself.state=stateifself.prev_state!=state:self.__reset_msg_printing(self.prev_state)ifself.__actionisnotNone:assertisinstance(self.__cur_feasible_actions_status,dict)self.__cur_feasible_actions_status['selected_interaction'].reset_state()self.__action=Noneself.__cur_feasible_actions_status=Noneifself.initial_stateisNone:self.initial_state=stateelse:raiseValueError("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.
defreset_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_stateself.limbo_state=Noneself.prev_state=Noneself.__action=Noneself.__cur_feasible_actions_status=Noneforactinself.__id_to_action:act.clear_interactions()act.system_interaction.reset_state()act.reset_msg_printing()forsinself.__id_to_state:s.reset()ifs.actionisnotNone: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.
defshow_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.
defshow_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.
defshow_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.
defset_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=yesifyes: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 messagesself.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 messagesiflen(self.__id_to_original_state_msg)>0:fori,stateinenumerate(self.__id_to_state):state.set_msg(self.__id_to_original_state_msg[i][0])ifstate.actionisnotNone:state.action.set_msg(self.__id_to_original_state_msg[i][1])iflen(self.__id_to_original_action_msg)>0:fori,actioninenumerate(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 messagesself.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.
defgenerate_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. """ifstatesisTrueandlen(self.__id_to_original_state_msg)==0:forstateinself.__id_to_state:original1=state.msg_with_wildcardsoriginal2=state.action.msg_with_wildcardsifstate.actionisnotNoneelseNoneifstate.msg_with_wildcardsisNone:state.set_msg("📍 "+state.name.replace('_',' ').capitalize())elifforce:state.set_msg("📍 "+state.name.replace('_',' ').capitalize()+" ["+state.msg_with_wildcards+"]")ifstate.actionisnotNone:ifstate.action.msg_with_wildcardsisNone:state.action.set_msg("📍 "+state.action.name.replace('_',' ').capitalize())elifforce:state.action.set_msg("📍 "+state.action.name.replace('_',' ').capitalize()+" ["+state.action.msg_with_wildcards+"]")self.__id_to_original_state_msg.append((original1,original2))ifactionsisTrueandlen(self.__id_to_original_action_msg)==0:foractioninself.__id_to_action:original=action.msg_with_wildcardsifaction.msg_with_wildcardsisNone:action.set_msg("🚀 "+action.name.replace('_',' ').capitalize())elifforce: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.
defprint_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.stateifself.stateisnotNoneelseself.limbo_state)ifstateisNoneelsestateassertstateisnotNoneforto_state,action_listinself.transitions[state].items():ifaction_listisNoneorlen(action_list)==0:log.user(f"{state}, no actions")else:foractioninaction_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.
defto_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 onlyteleport_inv_transitions={}action_that_are_teleports=[]forsrc,destsinself.transitions.items():fordest,actionsindests.items():ifdest==src:continue# Skipping self loops for teleports (they should not be there at all, if so, we filter)foractinactions:ifact.is_teleport():action_that_are_teleports.append(act)ifdestnotinteleport_inv_transitions:teleport_inv_transitions[dest]={}ifsrcnotinteleport_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 teleportteleport_transitions={Custom.ALL_STATES_NAME:{}}# Keep "all" on top (it is handled like a new state)fordest,srcsinteleport_inv_transitions.items():# For each source state reaching the current destination...forsrc,teleportsinsrcs.items():# For each teleport linking source to the current destination...fortelinteleports:iftel.get_mark()=="considered":# Skipping already considered onescontinuetel.set_mark("considered")# Markingtel_to_list=tel.to_list()_found_teleports=[(src,tel)]# Let's see if a teleport equivalent to the considered one connects all sourcesfor_src,_teleportsinsrcs.items():ifsrc==_src:continue# Already considered case_found=Falsefor_telin_teleports:if_tel.get_mark()=="considered":# Skipping already considered onescontinueiftel_to_list==_tel.to_list():_tel.set_mark("considered")# Marking_found_teleports.append((_src,_tel))_found=Truebreakifnot_found:break# Distinguishingiflen(_found_teleports)==(len(self.states)-1):ifCustom.ALL_STATES_NAMEnotinteleport_transitions:teleport_transitions[Custom.ALL_STATES_NAME]={}ifdestnotinteleport_transitions[Custom.ALL_STATES_NAME]:teleport_transitions[Custom.ALL_STATES_NAME][dest]=[]teleport_transitions[Custom.ALL_STATES_NAME][dest].append(tel)# Append a single oneelse:for_src,_telin_found_teleports:if_srcnotinteleport_transitions:teleport_transitions[_src]={}ifdestnotinteleport_transitions[_src]:teleport_transitions[_src][dest]=[]teleport_transitions[_src][dest].append(_tel)# Clearing markfortelinaction_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")ifself.welcome_msg_with_wildcardsisnotNoneelseNone,'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()forstateinself.__id_to_state},'transitions':{from_state:[{"on":act.to_dict(),"goto":to_state}forto_state,action_listinto_states.items()foractinaction_listifnotact.is_teleport()]forfrom_state,to_statesinself.transitions.items()iflen(to_states)>0},'teleports':{from_state:[{"on":act.to_dict(),"goto":to_state}forto_state,action_listinto_states.items()foractinaction_list]forfrom_state,to_statesinteleport_transitions.items()iflen(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.
defsave(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. """ifonly_if_changedisnotNoneandos.path.exists(filename):try:existing=HybridStateMachine(agent=only_if_changed).load(filename)ifstr(existing)==str(self):returnFalseexceptExceptionase:# If load fails, we assume it changedlog.error(f"Error while reloading the exising machine from {filename}, "f"assuming it changed: {e}")withopen(filename,'w',encoding='utf-8')asfile:file.write(str(self))returnTrue
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.
defload(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 fileif(isinstance(filename_or_hsm_as_string,Traversable)orisinstance(filename_or_hsm_as_string,io.TextIOWrapper)):# Safe way to load when this file is packed in a pip packagehsm_data=json.load(filename_or_hsm_as_string)# noqaelse:# Ordinary caseifos.path.exists(filename_or_hsm_as_string)andos.path.isfile(filename_or_hsm_as_string):# noqawithopen(filename_or_hsm_as_string,'r',encoding="utf-8")asfile:# noqahsm_data=json.load(file)else:# Assuming it is a stringhsm_data=json.loads(filename_or_hsm_as_string)# noqa# Backward compatibilityif"machine"notinhsm_data:returnself.load_backward_compat(hsm_data)# Getting state infotry:self.initial_state=hsm_data['machine']['initial_state']self.state=self.initial_stateself.prev_state=Noneself.limbo_state=Noneself.set_welcome_message(hsm_data['machine'].get('msg',None))self.set_role(hsm_data['machine']['role'])# Do it AFTER having set the welcome messageself.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))exceptExceptionase:log.critical(f"Invalid JSON data format when loading the state machine [{e}]")self.states={}self.transitions={}# Getting statesif'states'notinhsm_data:log.critical(f"Invalid JSON data format when loading the state machine (missing state list)")forstate,state_actioninhsm_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.forkinCustom.TIME_TO_WAIT_BEFORE_ACTING_ARG_NAMES:ifkinstate_action:waiting_time=state_action[k]breakself.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'inhsm_data:forfrom_state,list_of_to_state_dictsinhsm_data['transitions'].items():forto_state_dictinlist_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.forkinCustom.SECONDS_ARG_NAMES:ifkinaction_dict:total_time=action_dict[k]breaktimeout=0.forkinCustom.TIMEOUT_ARG_NAMES:ifkinaction_dict:timeout=action_dict[k]breakdelay=0.forkinCustom.DELAY_ARG_NAMES:ifkinaction_dict:delay=action_dict[k]breakself.add_transit(from_state,to_state,action=act_name,args=act_args,ready=act_ready,msg=msg,avoid_changing_ready="ready"inaction_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'inhsm_data:# Replicating the "all" teleport over all source statesifCustom.ALL_STATES_NAMEinhsm_data['teleports']:list_of_to_state_dicts=hsm_data['teleports'][Custom.ALL_STATES_NAME]forto_state_dictinlist_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.forkinCustom.SECONDS_ARG_NAMES:ifkinaction_dict:total_time=action_dict[k]breaktimeout=0.forkinCustom.TIMEOUT_ARG_NAMES:ifkinaction_dict:timeout=action_dict[k]breakdelay=0.forkinCustom.DELAY_ARG_NAMES:ifkinaction_dict:delay=action_dict[k]break# Looping over all statesforfrom_state_objinself.__id_to_state:from_state=from_state_obj.name# Skipping the destination stateiffrom_state==to_state:continueself.add_transit(from_state,to_state,action=act_name,args=act_args,ready=act_ready,msg=msg,avoid_changing_ready="ready"inaction_dict,teleport=True,high_priority=high_priority,total_time=total_time,timeout=timeout,delay=delay)# Handling all the ordinary teleportsforfrom_state,list_of_to_state_dictsinhsm_data['teleports'].items():# Skipping "all"-like teleport (already handled)iffrom_state==Custom.ALL_STATES_NAME:continueforto_state_dictinlist_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.forkinCustom.SECONDS_ARG_NAMES:ifkinaction_dict:total_time=action_dict[k]breaktimeout=0.forkinCustom.TIMEOUT_ARG_NAMES:ifkinaction_dict:timeout=action_dict[k]breakdelay=0.forkinCustom.DELAY_ARG_NAMES:ifkinaction_dict:delay=action_dict[k]breakself.add_transit(from_state,to_state,action=act_name,args=act_args,ready=act_ready,msg=msg,avoid_changing_ready="ready"inaction_dict,teleport=True,high_priority=high_priority,total_time=total_time,timeout=timeout,delay=delay)returnself
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().
defload_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 infoself.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_messageself.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 statesself.states={}if'state_actions'inhsm_data:forstate,state_action_listinhsm_data['state_actions'].items():iflen(state_action_list)==3:# Backward compatibilityact_name,act_args,state_id=state_action_listwaiting_time=0.blocking=Truemsg=Noneeliflen(state_action_list)==4:# Backward compatibilityact_name,act_args,state_id,waiting_time_or_blocking=state_action_listifisinstance(waiting_time_or_blocking,bool):waiting_time=0.blocking=waiting_time_or_blockingelse:waiting_time=waiting_time_or_blockingblocking=Truemsg=Noneeliflen(state_action_list)==5:# Backward compatibilityact_name,act_args,state_id,blocking,waiting_time=state_action_listmsg=Noneelse: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_idifstate_id>=0elseNone,waiting_time=waiting_time,blocking=blocking,msg=msg)# Getting transitionsself.transitions={}forfrom_state,to_statesinhsm_data['transitions'].items():forto_state,action_listinto_states.items():foraction_list_tupleinaction_list:iflen(action_list_tuple)==4:act_name,act_args,act_ready,act_id=action_list_tuplemsg=Noneelse: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_idifact_id>=0elseNone,msg=msg,avoid_changing_ready=True)returnself
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.
defto_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')forstate,state_objinself.states.items():action=state_obj.actionifactionisnotNone:s="("fori,(k,v)inenumerate(action.args.items()):s+=str(k)+"="+(str(v)ifnotisinstance(v,str)else("'"+v+"'"))ifi<len(action.args)-1:s+=", "s+=")"label=action.name+siflen(label)>40:tokens=label.split(" ")z=""i=0done=Falsewhilei<len(tokens):z+=(" "ifi>0else"")+tokens[i]ifnotdoneandi<(len(tokens)-1)andlen(z+tokens[i+1])>40:z+="\n "done=Truei+=1label=zsuffix="\n"+labelelse:suffix=""ifstate==self.initial_state:graph.attr('node',shape='diamond')else:graph.attr('node',shape='oval')ifself.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)})forfrom_state,to_statesinself.transitions.items():j=1forto_state,action_listinto_states.items():loop_groups={}# (style, color) -> [merged label, id of first action]foractioninaction_list:args=action.argss="("fori,(k,v)inenumerate(args.items()):s+=str(k)+"="+(str(v)ifnotisinstance(v,str)else("'"+str(v)+"'"))ifi<len(args)-1:s+=", "s+=")"special_args={}ifisinstance(action.get_total_time(),str)oraction.get_total_time()>0:total_time=action.get_total_time()special_args[Custom.SECONDS_ARG_NAMES[0]]=total_timeifisinstance(action.get_timeout(),str)oraction.get_timeout()>0.:timeout=action.get_timeout()special_args[Custom.TIMEOUT_ARG_NAMES[0]]=timeoutifisinstance(action.get_delay(),str)oraction.get_delay()>0.:delay=action.get_delay()special_args[Custom.DELAY_ARG_NAMES[0]]=delayiflen(special_args)>0:s+="\n["fori,(k,v)inenumerate(special_args.items()):s+=str(k)+"="+(str(v)ifnotisinstance(v,str)else("'"+str(v)+"'"))ifi<len(special_args)-1:s+=", "s+="]"label=str(j)+"."+action.name+sj+=1iflen(label)>40:tokens=label.split(" ")z=""i=0done=Falsewhilei<len(tokens):z+=(" "ifi>0else"")+tokens[i]ifnotdoneandi<(len(tokens)-1)andlen(z+tokens[i+1])>40:z+="\n"done=Truei+=1label=zedge_style='dashed'ifnotaction.is_ready()else'solid'edge_color="#00000050"ifaction.is_teleport()else"#000000"iffrom_state==to_stateandlen(action_list)>1:group=loop_groups.setdefault((edge_style,edge_color),["",action.id])group[0]+=("\n"ifgroup[0]else"")+labelelse: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)inloop_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)})returngraph
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>.
defsave_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. """iffilename.lower().endswith(".pdf"):filename=filename[0:-4]try:self.to_graphviz().render(filename,format='pdf',cleanup=True)returnTrueexceptExceptionase:log.error(f"Error while saving to PDF {e}")returnFalse
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/.
defset_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.
defset_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_fcnself.policy_filter_opts=filter_fcn_optsself.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.
defset_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`. """ifobjisNone: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 rememberself.agent=objforstate_objinself.states.values():ifstate_obj.actionisnotNone:state_obj.action.agent=objforaction_objinself.__id_to_action:ifaction_objisnotNone: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.