unaiverse.hsm.action
What this module does 🔴
Defines the Action abstraction used by the hybrid state machine to bind callables to transitions, manage timing/timeouts, wildcards, and an ordered list of pending interactions per requester.
action
¶
█████ █████ ██████ █████ █████ █████ █████ ██████████ ███████████ █████████ ██████████
░░███ ░░███ ░░██████ ░░███ ░░███ ░░███ ░░███ ░░███░░░░░█░░███░░░░░███ ███░░░░░███░░███░░░░░█
░███ ░███ ░███░███ ░███ ██████ ░███ ░███ ░███ ░███ █ ░ ░███ ░███ ░███ ░░░ ░███ █ ░
░███ ░███ ░███░░███░███ ░░░░░███ ░███ ░███ ░███ ░██████ ░██████████ ░░█████████ ░██████
░███ ░███ ░███ ░░██████ ███████ ░███ ░░███ ███ ░███░░█ ░███░░░░░███ ░░░░░░░░███ ░███░░█
░███ ░███ ░███ ░░█████ ███░░███ ░███ ░░░█████░ ░███ ░ █ ░███ ░███ ███ ░███ ░███ ░ █
░░████████ █████ ░░█████░░████████ █████ ░░███ ██████████ █████ █████░░█████████ ██████████
░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░░ ░░░ ░░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░░ ░░░░░░░░░░
A Collectionless AI Project (https://collectionless.ai)
Registration/Login: https://unaiverse.io
Code Repositories: https://github.com/collectionlessai/
Main Developers: Stefano Melacci (Project Leader), Christian Di Maio, Tommaso Guidi
Action
¶
Action(name: str, args: dict, actionable: object, idx: int = -1, ready: bool = True, msg: str | None = None, avoid_changing_ready: bool = False, teleport: bool = False, high_priority: bool = False, max_duration: float | str = 0.0, retry_timeout: float | str = 0, delay: float | str = 0)
A single executable action inside a Hybrid State Machine (HSM) state.
An Action wraps a named method on an actionable object together with a fixed set
of keyword arguments and a collection of time-based constraints (maximum duration,
retry timeout, delay). The HSM schedules and dispatches actions; calling an instance
directly (via __call__) runs the underlying method and returns a status code that
tells the HSM whether to retry, move on, or mark the step as done.
Actions are either inner-ready (the HSM can execute them autonomously) or
outer-ready (they require an external Interaction request to be triggered). The
two flags (inner / outer) are set on construction and can be changed at runtime
with set_as_ready and set_as_not_ready. A high-priority flag (high_priority)
is a hint to the policy to prefer this action over others in the same state.
Wildcard placeholders (strings matching <name> patterns) may appear in args,
msg, and the time parameters. When set_state_machine registers the parent
HybridStateMachine, its wildcard table is applied to expand all placeholders to
concrete values. The expansion can be re-applied later via apply_wildcards.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Name of the underlying callable on |
|
args |
Keyword arguments passed to the callable, after wildcard expansion. |
|
actionable |
The object that owns the method named |
|
interactions |
The |
|
id |
Optional unique integer ID (-1 when not needed). |
|
msg |
Optional human-readable description logged when the action runs. |
|
inner |
True when the action can be executed autonomously (inner readiness). |
|
outer |
True when the action accepts external interaction requests. |
|
state_machine |
The parent |
|
teleport |
When True the action is hidden from the drawn state-machine diagram. |
|
high_priority |
When True the policy prefers this action over lower-priority peers. |
|
param_list |
Ordered list of parameter names accepted by the underlying callable. |
|
param_to_default_value |
Mapping from parameter name to its default value. |
|
wildcards |
Mapping from placeholder strings to their concrete replacement values. |
|
args_with_wildcards |
Backup of |
|
msg_with_wildcards |
Backup of |
|
system_interaction |
The synthetic |
Examples:
The framework constructs Action objects automatically when loading HSM
behaviour definitions. Direct construction is rarely needed outside tests:
>>> class MyAgent:
... async def greet(self, name: str = "world") -> bool:
... print(f"Hello, {name}!")
... return True
>>>
>>> agent = MyAgent()
>>> action = Action(name="greet", args={"name": "Alice"}, actionable=agent)
>>> action.get_name()
'greet'
>>> action.is_ready()
True
Initialize an Action wrapping a named method on actionable.
Resolves the callable from actionable via getattr, inspects its signature
to populate param_list and param_to_default_value, and extracts any
time-based parameters (max_duration, retry_timeout, delay) from
args when the corresponding wildcard keys are present. If any parameter in the
callable's signature belongs to Custom.INTERACTION_INJECT_NAMES and
avoid_changing_ready is False, the action is forced to outer-only mode
(inner=False, outer=True) so it waits for an external Interaction.
HTML entities in msg are unescaped via html.unescape before storage.
A lightweight system_interaction is built at the very end of initialization
so that the action can be dispatched autonomously without an external requester.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the method to look up on |
required |
args
|
dict
|
Keyword arguments to pass to the method. Special time-related keys
(see |
required |
actionable
|
object
|
Object on which the method named |
required |
idx
|
int
|
Optional unique integer ID for this action. Defaults to -1. |
-1
|
ready
|
bool
|
Initial inner-readiness flag. Defaults to True. |
True
|
msg
|
str | None
|
Optional human-readable description logged when the action runs. HTML entities are unescaped automatically. Defaults to None. |
None
|
avoid_changing_ready
|
bool
|
When True, suppresses the automatic override that forces outer-only mode for interaction-injecting parameters. Defaults to False. |
False
|
teleport
|
bool
|
When True, the action is hidden from the state-machine diagram. Defaults to False. |
False
|
high_priority
|
bool
|
When True, the policy prefers this action over others. Defaults to False. |
False
|
max_duration
|
float | str
|
Maximum wall-clock seconds the action may run before the HSM
considers it expired. Values <= 0 mean no limit. May be a wildcard
string (e.g. |
0.0
|
retry_timeout
|
float | str
|
Maximum seconds the HSM keeps re-attempting this action before giving up. Values <= 0 mean no timeout. May be a wildcard string. Defaults to 0. |
0
|
delay
|
float | str
|
Seconds that must elapse after entering the parent state before this action is considered for execution. Values <= 0 mean no delay. May be a wildcard string. Defaults to 0. |
0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If any key in |
Source code in unaiverse/hsm/action.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
ready
property
¶
Return the inner readiness flag of the action.
This property exposes the inner attribute, which is True when the action
can be dispatched autonomously by the HSM without an external Interaction.
Use is_ready for a full readiness check that also accounts for pending
interactions and the configured delay.
Returns:
| Type | Description |
|---|---|
bool
|
True if the action is inner-ready, False otherwise. |
is_high_priority
property
¶
Return whether the action is marked as high priority.
High-priority actions are preferred by the policy over other actions in the same
HSM state when multiple actions are simultaneously ready. The flag is set at
construction time or via set_high_priority.
Returns:
| Type | Description |
|---|---|
bool
|
True if the action is high priority, False otherwise. |
set_high_priority
¶
Mark the action as high priority.
Sets high_priority to True, signalling to the HSM policy that this action
should be preferred over non-high-priority actions in the same state when
multiple are ready at the same time. See also is_high_priority.
Source code in unaiverse/hsm/action.py
set_state_machine
¶
Register the parent state machine that owns this action.
Stores a reference to hsm in state_machine and immediately calls
set_wildcards with the wildcards from hsm.get_wildcards(), so that all
placeholder values in args, msg, and the time parameters are resolved to
their concrete values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsm
|
object
|
The |
required |
Source code in unaiverse/hsm/action.py
get_name
¶
Return the name of the underlying callable.
Returns:
| Type | Description |
|---|---|
str
|
The string name of the method on |
set_mark
¶
Store an arbitrary marker object on the action.
The mark is a lightweight tag that the HSM or external code can attach to an
action for bookkeeping purposes (for example, to associate a state transition
token). It has no effect on action scheduling or dispatch. Use get_mark to
retrieve the stored value and clear_mark to reset it to None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mark
|
object
|
Any object to store as the marker. |
required |
Source code in unaiverse/hsm/action.py
get_mark
¶
Return the marker object previously stored by set_mark.
Returns None when no mark has been set or after clear_mark has been
called.
Returns:
| Type | Description |
|---|---|
object
|
The stored marker object, or |
Source code in unaiverse/hsm/action.py
clear_mark
¶
Clear the marker object stored on the action.
Resets the internal mark to None. Equivalent to calling
set_mark(None). This is called automatically at the end of each action
invocation to prevent stale marks from leaking across execution rounds.
Source code in unaiverse/hsm/action.py
to_code_str
¶
Return a compact code-style string representation of the action for logging.
The format is aai:<name>|<args>| followed by one indented line per pending
interaction (using each interaction's own to_code_str representation), or the
suffix no-int when no interactions are present.
Returns:
| Type | Description |
|---|---|
str
|
A single- or multi-line string summarising the action and its interactions. |
Source code in unaiverse/hsm/action.py
set_as_ready
¶
Set the action to inner-ready mode, enabling autonomous execution.
Sets inner to True and outer to False. In this mode the HSM can
dispatch the action without waiting for an external Interaction. Accepting
external requests is disabled (outer=False) to prevent double-dispatching for
actions that are already unconditionally available. See also set_as_not_ready.
Source code in unaiverse/hsm/action.py
set_as_not_ready
¶
Set the action to outer-only mode, requiring an external interaction to run.
Sets inner to False and outer to True. In this mode the action
will not be dispatched autonomously; it must be explicitly requested by an
external agent via an Interaction. See also set_as_ready.
Source code in unaiverse/hsm/action.py
set_msg
¶
Set the human-readable message associated with this action.
HTML entities in msg are automatically unescaped via html.unescape before
storage. Both msg and msg_with_wildcards are updated together so that
subsequent wildcard expansions (apply_wildcards) start from the new value.
Passing None clears any previously set message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str | None
|
The new message string, or |
required |
Source code in unaiverse/hsm/action.py
is_ready
¶
Return True if the action is eligible for execution right now.
An action is considered ready when all of the following conditions hold:
- The configured delay has elapsed (or no delay is set). The delay is measured
from
delay_starting_timeusingtime.perf_counter(). -
At least one of the following sub-conditions is true:
-
innerisTrue(the action can run autonomously), or consider_interactionsisTrue,outerisTrue, and at least one doable interaction exists ininteractions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consider_interactions
|
bool
|
When |
True
|
delay_starting_time
|
float
|
The |
-1.0
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the action is eligible for execution, False otherwise. |
Source code in unaiverse/hsm/action.py
is_teleport
¶
Return whether this action is a teleport action.
Teleport actions are hidden from the state-machine diagram rendered by the framework. They are typically used for instantaneous, bookkeeping-only transitions that do not represent meaningful user-visible behaviour.
Returns:
| Type | Description |
|---|---|
bool
|
True if the action is a teleport action, False otherwise. |
Source code in unaiverse/hsm/action.py
allows_outer_interactions
¶
Return whether the action accepts externally triggered interactions.
When True (outer=True), external agents may push Interaction requests
into the action's interactions list, and the action becomes eligible for
dispatch when at least one doable interaction is present. When False, calls
to add_interaction are silently rejected.
Returns:
| Type | Description |
|---|---|
bool
|
True if the action accepts outer interactions, False otherwise. |
Source code in unaiverse/hsm/action.py
allows_inner_interactions
¶
Return whether the action can be dispatched autonomously by the HSM.
When True (inner=True), the HSM may execute the action without any
external Interaction request. This corresponds to the ready property.
Returns:
| Type | Description |
|---|---|
bool
|
True if the action can be triggered internally, False otherwise. |
Source code in unaiverse/hsm/action.py
set_timeout
¶
Set the retry timeout to a custom value.
Overrides the timeout configured at construction time or via the args dict.
The timeout controls how long the HSM keeps re-attempting this action before
giving up. A value <= 0 disables the timeout. See also set_default_timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
retry_timeout
|
float
|
Maximum seconds to retry the action. Values <= 0 disable the timeout entirely. |
required |
Source code in unaiverse/hsm/action.py
set_default_timeout
¶
Reset the retry timeout to the framework-wide default value.
Sets the internal timeout to Custom.DEFAULT_TIMEOUT, overriding any value
that was previously set at construction time, via args, or by a call to
set_timeout. See also set_timeout.
Source code in unaiverse/hsm/action.py
is_pedantic
¶
Return whether a retry timeout is configured for this action.
An action is pedantic when retry_timeout is greater than zero, meaning the
HSM will keep re-attempting it rather than skipping it immediately on failure.
Non-pedantic actions (retry_timeout <= 0) are skipped after the first failed
execution attempt.
Returns:
| Type | Description |
|---|---|
bool
|
True if a positive retry timeout has been configured, False otherwise. |
Source code in unaiverse/hsm/action.py
get_total_time
¶
Return the maximum wall-clock duration configured for this action.
Values greater than zero cap the total time the action may run. A value of 0
(or any value <= 0) means there is no upper time limit. When the parameter was
specified as a wildcard placeholder string (e.g. "<max_time>"), the raw
wildcard string is returned until apply_wildcards has resolved it.
Returns:
| Type | Description |
|---|---|
float | str
|
The maximum duration in seconds as a |
float | str
|
|
Source code in unaiverse/hsm/action.py
get_timeout
¶
Return the retry timeout configured for this action.
The retry timeout is the maximum number of seconds the HSM keeps re-attempting
this action before giving up. A value of 0 (or any value <= 0) disables the
timeout. When the parameter was specified as a wildcard placeholder string, the
raw string is returned until apply_wildcards has resolved it. See also
is_pedantic and set_timeout.
Returns:
| Type | Description |
|---|---|
float | str
|
The retry timeout in seconds as a |
float | str
|
|
Source code in unaiverse/hsm/action.py
get_delay
¶
Return the entry delay configured for this action.
The delay is the number of seconds that must elapse after the parent HSM state is
entered before this action becomes eligible for execution. A value of 0 (or
any value <= 0) means the action is immediately eligible. When the parameter was
specified as a wildcard placeholder string, the raw string is returned until
apply_wildcards has resolved it.
Returns:
| Type | Description |
|---|---|
float | str
|
The delay in seconds as a |
float | str
|
the value has not yet been resolved. |
Source code in unaiverse/hsm/action.py
to_list
¶
Return a flat list snapshot of the action's properties for serialization or comparison.
The returned list has the fixed layout:
[name, args, inner, outer, total_time, retry_timeout, delay, msg].
Time fields (total_time, retry_timeout, delay) are normalized to
0. when their value is a non-positive number, so comparisons against the
default "no limit" state are straightforward. Wildcard placeholder strings are
kept as-is. See also to_dict for a named-key representation.
Returns:
| Type | Description |
|---|---|
list
|
A list of eight elements containing the action's name, args dict, inner and |
list
|
outer readiness flags, time constraints, and message. |
Source code in unaiverse/hsm/action.py
to_dict
¶
Return a named-key dictionary snapshot of the action's properties for serialization.
The returned dictionary contains the keys "action", "action_kwargs",
"msg", "ready", "high_priority", and the canonical time-constraint
key names from Custom.SECONDS_ARG_NAMES[0], Custom.TIMEOUT_ARG_NAMES[0],
and Custom.DELAY_ARG_NAMES[0]. Non-ASCII characters in msg are encoded
as XML character references so the result is safe to embed in JSON or HTML. See
also to_list for a positional-list representation.
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary mapping property names to their current values. |
Source code in unaiverse/hsm/action.py
same_as
¶
Return whether this action matches the given name and argument subset.
Two actions are considered the same when all of the following hold:
- Their names are equal.
- Every key in
argsis a recognized parameter of this action (validated bycheck_provided_args). - For every key-value pair in
argsthat is not inCustom.RESERVED_IN_ACTION_KWARGS, the value matches the corresponding value inself.args(when the key is present there).
Keys not present in args are assumed to match, so same_as accepts a
subset of arguments. Reserved framework keys (time-based, sentinel, etc.) are
excluded from value comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The action name to compare against. |
required |
args
|
dict | None
|
A (possibly partial) argument dictionary to compare. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if this action is considered identical to the described action, False |
bool
|
otherwise. |
Source code in unaiverse/hsm/action.py
check_provided_args
¶
check_provided_args(args: dict, exception: bool = False, remove_special_arguments: bool = False) -> bool
Validate that every key in args is an accepted parameter for this action.
Each key is checked against the following categories in order:
- HSM transit meta names (
Custom.HSM_TRANSIT_META_NAMES): silently removed whenremove_special_argumentsisTrue; otherwise rejected. - Wire sentinels / injection names (
Custom.WIRE_SENTINEL_NAMES,Custom.INTERACTION_INJECT_NAMES): always rejected. - Interaction field names (
Custom.INTERACTION_FIELD_NAMES): always silently accepted (skipped). - Unknown names (not in
self.param_list): rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
dict
|
The keyword-argument dictionary to validate. The dictionary may be
mutated in-place when |
required |
exception
|
bool
|
When |
False
|
remove_special_arguments
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if every key is valid (or has been silently removed), False on the |
bool
|
first rejected key when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an invalid key is found and |
Source code in unaiverse/hsm/action.py
set_wildcards
¶
Store a new wildcard table for later expansion.
The wildcard table maps placeholder strings (typically in the <name> format)
to their concrete replacement values. Passing None clears the current table
(equivalent to an empty dict). The replacements are not applied immediately;
call apply_wildcards afterward to expand all placeholders in args,
msg, and the time parameters. set_state_machine calls this method
automatically when the action is registered with a parent
HybridStateMachine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wildcards
|
dict[str, str | float | int] | None
|
A mapping from placeholder strings to concrete replacement
values ( |
required |
Source code in unaiverse/hsm/action.py
add_interaction
¶
add_interaction(interaction: Interaction) -> bool
Add a pending external interaction request to this action.
Registers interaction as a pending request by attaching a back-reference to
this action (via interaction.set_action_ref) and appending it to the internal
ActionInteractionList. If the action does not accept outer interactions
(outer=False), the call is a no-op and False is returned. Once at least
one doable interaction is present, the action becomes ready for execution (see
is_ready). See also clear_interactions and clear_interaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interaction
|
Interaction
|
The |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the interaction was added, False if the action does not accept outer |
bool
|
interactions. |
Source code in unaiverse/hsm/action.py
clear_interactions
¶
Remove pending interaction requests from this action.
When requester is None, all pending interactions are discarded and the
internal ActionInteractionList is replaced with a fresh empty one. When
requester is provided, only the interactions belonging to that requester are
removed, leaving interactions from other requesters untouched. See also
clear_interaction for removing a single specific interaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str | None
|
The peer ID whose interactions should be removed, or |
None
|
Source code in unaiverse/hsm/action.py
clear_interaction
¶
Remove a single specific interaction identified by its requester and insertion-order ID.
Looks up the interaction at position req_id in the per-requester sub-list and
removes it from the internal ActionInteractionList. If no such interaction
exists the call is a no-op. See also clear_interactions for bulk removal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str
|
The peer ID of the requester who owns the interaction. |
required |
req_id
|
int
|
The per-requester insertion-order index of the interaction to remove. |
required |
Source code in unaiverse/hsm/action.py
get_list_of_interactions
¶
get_list_of_interactions() -> ActionInteractionList
Return the ActionInteractionList holding all pending interaction requests.
The returned object provides fine-grained access to pending requests: filter by
requester, retrieve by insertion order, check doability, or iterate over all
stored Interaction objects. The list is live - mutations affect the action's
internal state directly. See add_interaction and clear_interactions for
the standard way to add or remove entries.
Returns:
| Type | Description |
|---|---|
ActionInteractionList
|
The |
Source code in unaiverse/hsm/action.py
get_actual_params
¶
Resolve the full set of keyword arguments to pass to the underlying callable.
Builds the final argument dictionary by consulting, in priority order:
self.args- the action's own stored arguments (highest priority).additional_args- extra arguments supplied at call time (e.g. from an incomingInteraction'saction_kwargs).self.param_to_default_value- default values from the method signature.
Only parameters listed in self.param_list are included. If a required
parameter has no value in any of the three sources, an error is logged and
None is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
additional_args
|
dict | None
|
A supplementary keyword-argument dictionary merged after
|
required |
Returns:
| Type | Description |
|---|---|
dict | None
|
A dictionary mapping every parameter name to its resolved value, or |
dict | None
|
|
Source code in unaiverse/hsm/action.py
apply_wildcards
¶
Expand all wildcard placeholders using the current wildcards table.
Re-reads the pre-expansion backups (args_with_wildcards and
msg_with_wildcards) and rebuilds args and msg with every placeholder
string replaced by its concrete value from wildcards. Wildcard substitution
also covers max_duration, retry_timeout, and delay when those were
originally provided as placeholder strings (e.g. "<max_time>"). String
wildcards support partial replacement (substring match); non-string wildcards are
replaced only when the entire value equals the placeholder.
After expansion, __build_system_interaction is called so the
system_interaction reflects the post-expansion args (important when
args contains interaction-shaping keys such as streams or num_steps).
This method is called automatically by set_state_machine and should be called
again whenever the wildcard table is updated.
Note
The backup fields (args_with_wildcards, msg_with_wildcards) are
never mutated by this method, so apply_wildcards can be called multiple
times safely to re-apply a changed wildcard table.
Source code in unaiverse/hsm/action.py
ActionInteractionList
¶
An ordered, dual-indexed container for the Interaction objects pending on an Action.
ActionInteractionList maintains two parallel indices over the same set of
Interaction objects:
- Global insertion order (
by_insertion_order): a flat list that records every interaction in the order it was added. Used to iterate over all pending requests, retrieve the oldest or most-recent entry, and enforce the wall-clock timeout viaremove_due_to_timeout. - Per-requester insertion order (
by_requester_and_by_insertion_order): a dictionary keyed by requester peer ID, each value being the sub-list of that requester's interactions in insertion order. Used to retrieve, move, or remove a specific requester's requests efficiently.
Both indices are kept in sync on every add and remove operation by adjusting
the by_insertion_order_id and by_requester_insertion_order_id attributes
stored directly on each Interaction object.
An optional per-requester cap (max_per_requester) evicts the oldest entry for a
requester whenever the cap would be exceeded on add.
Attributes:
| Name | Type | Description |
|---|---|---|
by_insertion_order |
Flat list of all interactions in global insertion order. |
|
by_requester_and_by_insertion_order |
Mapping from requester peer ID to the sub-list of that requester's interactions. |
|
max_per_requester |
Maximum interactions stored per requester, or |
|
by_insertion_order_entering_time |
Parallel list of |
Examples:
>>> from unittest.mock import MagicMock
>>> il = ActionInteractionList(max_per_requester=2)
>>> inter = MagicMock()
>>> inter.requester = "agent_1"
>>> inter.uuid = "abc"
>>> inter.running = False
>>> inter.is_valid.return_value = True
>>> il.add(inter)
>>> len(il)
1
>>> il.is_requester_known("agent_1")
True
Initialize an empty interaction list with an optional per-requester cap.
Both the global insertion-order list and the per-requester index start empty. The entering-time list is also initialized empty and grows in lockstep with the global insertion-order list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_per_requester
|
int
|
Maximum number of interactions to retain per requester.
When a new interaction would exceed this limit, the oldest interaction
from that requester is evicted before the new one is added. |
-1
|
Source code in unaiverse/hsm/action.py
add
¶
add(interaction: Interaction) -> None
Append an interaction to the list, updating both internal indices.
Before appending, the list checks whether an interaction with the same requester and UUID already exists:
- If a duplicate is found and its
runningflag is set, the new interaction is silently dropped (the HSM is already handling that UUID). - If a duplicate is found but is not running, the existing slot is refreshed
in-place with the new
Interactionobject, preserving its position in both indices.
When no duplicate exists, the interaction is appended to both the global list and
the per-requester sub-list. If max_per_requester is positive and adding the
new entry would exceed the cap, the oldest entry for that requester is evicted
first via remove. The current time.perf_counter() timestamp is recorded
in by_insertion_order_entering_time for use by remove_due_to_timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interaction
|
Interaction
|
The |
required |
Source code in unaiverse/hsm/action.py
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 | |
remove
¶
remove(interaction: Interaction) -> None
Remove an interaction from the list and reindex all subsequent entries.
After deletion, every interaction that followed the removed entry in the global
list has its by_insertion_order_id decremented by one. The same reindexing
is applied to the per-requester sub-list. If the requester has no remaining
interactions, its key is deleted from by_requester_and_by_insertion_order.
The removed Interaction's index attributes are set to -1 to mark it as
invalidated. The call is a no-op when interaction.is_valid() returns
False.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interaction
|
Interaction
|
The |
required |
Source code in unaiverse/hsm/action.py
remove_due_to_timeout
¶
Remove all interactions that have been waiting longer than timeout_secs.
Compares each interaction's entering time (recorded in
by_insertion_order_entering_time at add time) against the current
time.perf_counter() value. Any interaction whose age (elapsed seconds since
entering) is greater than or equal to timeout_secs is collected and then
removed via remove. The two-phase collect-then-remove approach avoids
index corruption during iteration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout_secs
|
float
|
Maximum age in seconds. Interactions that have waited at least this long are evicted. |
required |
Source code in unaiverse/hsm/action.py
remove_completed
¶
Removes all interactions that have been marked as completed.
Source code in unaiverse/hsm/action.py
move_interaction_to_back
¶
move_interaction_to_back(interaction: Interaction) -> None
Moves an interaction to the back of the insertion-order list, preserving its original entering time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interaction
|
Interaction
|
The Interaction object to reposition. |
required |
Source code in unaiverse/hsm/action.py
move_requester_to_back
¶
Moves all interactions belonging to a requester to the back of the list, preserving their entering times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str
|
The peer ID whose interactions should be moved to the back. |
required |
Source code in unaiverse/hsm/action.py
get_interaction
¶
get_interaction(req_order_id: int, requester: str | None = None) -> Interaction | None
Retrieves an interaction by its insertion-order index, optionally scoped to a specific requester.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
req_order_id
|
int
|
The insertion-order index of the interaction to retrieve. |
required |
requester
|
str | None
|
If provided, scopes the lookup to the sub-list of this requester. |
None
|
Returns:
| Type | Description |
|---|---|
Interaction | None
|
The matching Interaction, or None if not found. |
Source code in unaiverse/hsm/action.py
get_oldest_interaction
¶
get_oldest_interaction(requester: str | None = None, ignore_completed: bool = False) -> Interaction | None
Returns the oldest (first-added) interaction, optionally scoped to a specific requester.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str | None
|
If provided, scopes the lookup to the sub-list of this requester. |
None
|
ignore_completed
|
bool
|
If True, completed interactions will be ignored/skipped. |
False
|
Returns:
| Type | Description |
|---|---|
Interaction | None
|
The oldest Interaction, or None if the list is empty. |
Source code in unaiverse/hsm/action.py
get_most_recent_interaction
¶
get_most_recent_interaction(requester: str | None = None, ignore_completed: bool = False) -> Interaction | None
Returns the most recently added interaction, optionally scoped to a specific requester.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str | None
|
If provided, scopes the lookup to the sub-list of this requester. |
None
|
ignore_completed
|
bool
|
If True, completed interactions will be ignored/skipped. |
False
|
Returns:
| Type | Description |
|---|---|
Interaction | None
|
The most recent Interaction, or None if the list is empty. |
Source code in unaiverse/hsm/action.py
get_interaction_by_uuid
¶
get_interaction_by_uuid(requester: str, uuid: str | None) -> Interaction | None
Finds the first interaction for a given requester that matches the specified UUID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str
|
The peer ID of the requester. |
required |
uuid
|
str | None
|
The UUID to search for (None is a valid UUID). |
required |
Returns:
| Type | Description |
|---|---|
Interaction | None
|
The matching Interaction, or None if not found. |
Source code in unaiverse/hsm/action.py
keep_only_the_most_recent_interaction
¶
Discards all interactions except the most recently added one, preserving its entering time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ignore_completed
|
bool
|
If True, completed interactions will be ignored/skipped. |
False
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in unaiverse/hsm/action.py
get_interactions
¶
get_interactions(requester: str | None = None, to_str: bool = False, doable_only: bool = False) -> list[Interaction] | str
Returns interactions, optionally filtered by requester or "do-ability", or as a JSON string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str | None
|
If provided, returns only interactions from this requester. |
None
|
to_str
|
bool
|
If True, returns a JSON-encoded string instead of a list. |
False
|
doable_only
|
bool
|
If True, filters to only interactions that pass |
False
|
Returns:
| Type | Description |
|---|---|
list[Interaction] | str
|
A list of Interaction objects, or a JSON-encoded string if |
Source code in unaiverse/hsm/action.py
clear
¶
Removes all interactions and resets all internal indices.
is_requester_known
¶
Checks whether any interactions from the given requester are currently stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requester
|
str
|
The peer ID to look up. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the requester has at least one interaction in the list, False otherwise. |