Skip to content

unaiverse.utils.misc

A collection of helpers that the node, the agent and the scripts of the examples share. They fall into six groups:

  1. Identity and keys: the public handle of an account, the identifier of a node and the UNaIVERSE key.
  2. Addresses: saving and reading the network addresses of running nodes.
  3. The code of a world: packing the source files of the roles, pruning them to what the roles import, loading a role from memory, hashing the definition of a world and screening the code for dangerous calls (see Worlds).
  4. Policy filters that delay the actions of an agent (see Behaviors).
  5. Terminal and file utilities: silencing output, a countdown, watching a JSON file or a folder, showing pictures.
  6. MultiPartLimitedDict, a dict with bounded partitions.

Identity and keys

owner_handle

owner_handle(static_profile: dict) -> str | None
Source code in unaiverse/utils/misc.py
def owner_handle(static_profile: dict) -> str | None:
    """The account's public identity: the nickname, with the e-mail address as a fallback
    for old servers or cached profiles (the address is not an identifier anymore)."""
    return static_profile.get('nickname') or static_profile.get('email')

Returns the public handle of an account from its static profile (a dict). The handle is the value of nickname when present and not empty. Otherwise it is the value of email and None when that is missing too. The e-mail address is the fallback for old servers and cached profiles. The agent, the world and the node call it.

build_unaid

build_unaid(profile, node_name: str | None = None)
Source code in unaiverse/utils/misc.py
def build_unaid(profile, node_name: str | None = None):
    if not hasattr(profile, "get_static_profile"):
        return None
    static_profile = profile.get_static_profile()
    if not isinstance(static_profile, dict):
        return None
    handle = owner_handle(static_profile)
    if handle is None:
        return None
    if node_name is None:
        if "node_name" not in static_profile:
            return None
        node_name = static_profile['node_name']
    return handle + '/' + node_name

Returns the identifier of a node in the form "<handle>/<node_name>" (for example "ada/hotel-concierge"). profile is an object with a method get_static_profile() that returns a dict. With node_name=None the name comes from the key node_name of the static profile. The function returns None in four cases: (1) the profile has no such method, (2) the static profile is not a dict, (3) owner_handle finds no handle and (4) no node name is available. AgentBasics and Node call it.

get_key_considering_multiple_sources

get_key_considering_multiple_sources(key_variable: str | None) -> str
Source code in unaiverse/utils/misc.py
def get_key_considering_multiple_sources(key_variable: str | None) -> str:
    """Retrieves the UNaIVERSE authentication key from one of several sources.

    Checks, in priority order: (1) the ``key_variable`` argument, (2) the ``NODE_KEY``
    environment variable, and (3) a cached key file.  If multiple sources are found,
    a warning is printed.  If no source is found, the user is prompted interactively and
    the entered key is saved to the cache file for future use.

    Args:
        key_variable: A key string passed directly from code, or None (and placeholder
            strings enclosed in ``<...>`` are also treated as None).

    Returns:
        The resolved authentication key string.
    """

    # Creating folder (if needed) to store the key
    try:
        key_dir = prepare_app_dir(app_name="UNaIVERSE")
    except Exception:
        raise GenException("Cannot create folder to store the key file")
    key_file = os.path.join(key_dir, "key")

    # Getting from an existing file
    key_from_file = None
    if os.path.exists(key_file):
        with open(key_file, "r") as f:
            key_from_file = f.read().strip()

    # Getting from env variable
    key_from_env = os.getenv("NODE_KEY", None)

    # Getting from code-specified option
    if key_variable is not None and len(key_variable.strip()) > 0:
        key_from_var = key_variable.strip()
        if key_from_var.startswith("<") and key_from_var.endswith(">"):  # Something like <UNAIVERSE_KEY_GOES_HERE>
            key_from_var = None
    else:
        key_from_var = None

    # Finding valid sources and checking if multiple keys were provided
    _keys = [key_from_var, key_from_env, key_from_file]
    _source_names = ["your code", "env variable 'NODE_KEY'", f"cache file {key_file}"]
    source_names = []
    mismatching = False
    multiple_source = False
    first_key = None
    first_source = None
    _prev_key = None
    for i, (_key, _source_name) in enumerate(zip(_keys, _source_names)):
        if _key is not None:
            source_names.append(_source_name)
            if _prev_key is not None:
                if _key != _prev_key:
                    mismatching = True
                multiple_source = True
                _prev_key = _key
            else:
                _prev_key = _key
                first_key = _key
                first_source = _source_name

    if len(source_names) > 0:
        if multiple_source and not mismatching:
            msg = "UNaIVERSE key (the exact same key) present in multiple locations: " + ", ".join(source_names)
            print(msg)
        if multiple_source and mismatching:
            assert isinstance(first_source, str)
            msg = "UNaIVERSE keys (different keys) present in multiple locations: " + ", ".join(source_names)
            msg += "\nLoaded the one stored in " + first_source
            print(msg)
        # if not multiple_source:
        #    msg = f"UNaIVERSE key loaded from {first_source}"
        #    print(msg)
        assert isinstance(first_key, str)
        return first_key
    else:

        # If no key present, ask user and save to file
        print("UNaIVERSE key not present in " + ", ".join(_source_names))
        print("If you did not already do it, go to https://unaiverse.io/me/security and generate a key")
        key = input("Enter your UNaIVERSE key, that will be saved to the cache file: ").strip()
        with open(key_file, "w") as f:
            f.write(key)
        return key

Returns the UNaIVERSE key of the user. The function looks at three sources in this order and returns the first one found:

  1. key_variable, the key passed in code. A blank string and a placeholder in angle brackets such as "<UNAIVERSE_KEY_GOES_HERE>" count as missing.
  2. The environment variable NODE_KEY.
  3. The cache file key in the application folder (~/.unaiverse/key on Linux and macOS, see prepare_app_dir).

When more than one source holds a key the function prints which sources hold one and whether the keys differ. An environment variable or a cache file that exists but is empty counts as a source and gives an empty key. Without any source the function asks for the key with input() on the terminal and writes it in plain text to the cache file. A folder that cannot be created raises GenException. Node.__init__ calls it with its argument unaiverse_key.

prepare_app_dir

prepare_app_dir(app_name: str = 'unaiverse') -> str
Source code in unaiverse/utils/misc.py
def prepare_app_dir(app_name: str = "unaiverse") -> str:
    """Resolves and creates the platform-appropriate application data directory.

    Args:
        app_name: Name of the application subdirectory (default: ``"unaiverse"``).

    Returns:
        The absolute path to the created directory.
    """
    app_name = app_name.lower()
    if os.name == "nt":  # Windows
        if os.getenv("APPDATA") is not None:
            key_dir = os.path.join(str(os.getenv("APPDATA")), "Local", app_name)  # Expected
        else:
            key_dir = os.path.join(str(Path.home()), f".{app_name}")  # Fallback
    else:  # Linux/macOS
        key_dir = os.path.join(str(Path.home()), f".{app_name}")
    os.makedirs(key_dir, exist_ok=True)
    return key_dir

Creates the folder of the application and returns its path. The name is lowercased. On Windows the folder is %APPDATA%\Local\<app_name>. Without APPDATA the fallback is %USERPROFILE%\.<app_name>. On the other systems it is ~/.<app_name>. The node keeps its identity there and the file transfers keep their Downloads folder there.

Addresses

save_node_addresses_to_file

save_node_addresses_to_file(node: Node, dir_path: str, public: bool, filename: str = 'addresses.txt', append: bool = False) -> None
Source code in unaiverse/utils/misc.py
def save_node_addresses_to_file(node: "Node", dir_path: str, public: bool,
                                filename: str = "addresses.txt", append: bool = False) -> None:
    """Writes the hosted node's name and its public or world addresses to a file.

    Args:
        node: The node object whose addresses are to be saved; expected to expose
            ``hosted.get_name()``, ``get_public_addresses()``, and ``get_world_addresses()``.
        dir_path: Directory in which the output file is created.
        public: If True, saves the public addresses; otherwise saves the world addresses.
        filename: Name of the output file (default: ``"addresses.txt"``).
        append: If True, appends to an existing file instead of overwriting it (default: False).
    """
    address_file = os.path.join(dir_path, filename)
    with open(address_file, "w" if not append else "a") as file:
        file.write(node.hosted.get_name() + ";" +
                   str(node.get_public_addresses() if public else node.get_world_addresses()) + "\n")
        file.flush()

Writes one line <name>;<addresses> to <dir_path>/<filename>. In this line <name> is the name of the hosted agent or world and <addresses> is the Python list of the public addresses of node (public=True) or of its world addresses (public=False). append=False (default) overwrites the file. The node calls it with filename="running.csv", public=True and append=True when the environment variable NODE_SAVE_RUNNING_ADDRESSES names an existing folder.

get_node_addresses_from_file

get_node_addresses_from_file(dir_path: str, filename: str = 'addresses.txt') -> dict[str, list[str]]
Source code in unaiverse/utils/misc.py
def get_node_addresses_from_file(dir_path: str, filename: str = "addresses.txt") -> dict[str, list[str]]:
    """Reads node names and their address lists from a file.

    Supports both the legacy single-address-per-line format (starting with ``"/"``) and the
    current ``name;[addr, ...]`` semicolon-separated format.

    Args:
        dir_path: Directory containing the file.
        filename: Name of the file to read (default: ``"addresses.txt"``).

    Returns:
        A dictionary mapping node names to lists of address strings.  Legacy files are
        returned under the key ``"unk"``.
    """
    ret = {}
    with open(os.path.join(dir_path, filename)) as file:
        lines = file.readlines()
        if not lines or len(lines) == 0:
            return ret

        # Old file format
        if lines[0].strip() == "/":
            addresses = []
            for line in lines:
                _line = line.strip()
                if len(_line) > 0:
                    addresses.append(_line)
            ret["unk"] = addresses
            return ret

        # New file format
        for line in lines:
            if line.strip().startswith("***"):  # Header marker
                continue
            comma_separated_values = [v.strip() for v in line.split(';')]
            node_name, addresses_str = comma_separated_values
            ret[node_name] = ast.literal_eval(addresses_str)  # Name appearing multiple times? the last entry is kept

    return ret

Reads a file written by save_node_addresses_to_file and returns a dict that maps each node name to its list of addresses. A name that appears twice keeps its last line. Lines that start with *** are skipped.

The function also reads an older format with one address per line and returns its addresses under the key "unk". It recognizes that format only when the first line is exactly /. A file of the old format that starts with an address raises ValueError (not enough values to unpack). An empty line in the current format raises the same error.

The code of a world

A world ships the Python files of its roles to every agent that joins. The world collects them with collect_py_files, keeps only what the roles import with prune_to_import_closure and packs them with pack_py_files. The joining node decodes them with unpack_py_files, checks them with analyze_code and builds its role with load_agent_in_memory without writing anything to disk.

collect_py_files

collect_py_files(folder: str, exclude_dirs: set[str] | None = None) -> dict[str, str]
Source code in unaiverse/utils/misc.py
def collect_py_files(folder: str, exclude_dirs: set[str] | None = None) -> dict[str, str]:
    """Collect all .py sources under *folder*, skipping named subdirectories.

    Args:
        folder: Root folder to walk.
        exclude_dirs: Sub-directory names to skip entirely (default: None).

    Returns:
        A dict mapping each file's path relative to *folder* (forward slashes,
        e.g. ``'role1.py'``, ``'utils/helper.py'``) to its source text.
    """
    if exclude_dirs is None:
        exclude_dirs = set()
    root = Path(folder)
    result: dict[str, str] = {}
    for py_file in root.rglob('*.py'):
        rel = py_file.relative_to(root)
        if any(part in exclude_dirs for part in rel.parts[:-1]):
            continue
        file_name_with_relative_path = str(rel).replace('\\', '/')
        result[file_name_with_relative_path] = py_file.read_text(encoding='utf-8')
    return result

Returns a dict that maps the path of every .py file under folder (recursive, relative to folder, with forward slashes, such as "utils/helper.py") to its source text. A file inside a folder whose name is in exclude_dirs (at any depth) is skipped.

pack_py_files

pack_py_files(py_files: dict[str, str]) -> str
Source code in unaiverse/utils/misc.py
def pack_py_files(py_files: dict[str, str]) -> str:
    """Serialize, gzip-compress and base64-encode a py-files dict.

    Args:
        py_files: Dict mapping relative paths to Python source text.

    Returns:
        A plain ASCII string suitable for embedding in any text-based message.
    """
    raw = json.dumps(py_files).encode('utf-8')
    return base64.b64encode(gzip.compress(raw)).decode('ascii')

Returns the dict of collect_py_files as an ASCII string: JSON, then gzip, then base64. The string can be sent inside any text message.

unpack_py_files

unpack_py_files(packed: str) -> dict[str, str]
Source code in unaiverse/utils/misc.py
def unpack_py_files(packed: str) -> dict[str, str]:
    """Base64-decode, decompress and deserialize a packed py-files string.

    Args:
        packed: A string produced by ``pack_py_files``.

    Returns:
        The original dict mapping relative paths to Python source text.
    """
    return json.loads(gzip.decompress(base64.b64decode(packed)).decode('utf-8'))

The inverse of pack_py_files. It returns the original dict and raises the error of base64, gzip or json on a string that is not the output of pack_py_files.

prune_to_import_closure

prune_to_import_closure(py_files: dict[str, str], entry_points: list[str], forced: tuple[str, ...] = ()) -> dict[str, str]
Source code in unaiverse/utils/misc.py
def prune_to_import_closure(py_files: dict[str, str], entry_points: list[str],
                            forced: tuple[str, ...] = ()) -> dict[str, str]:
    """Restrict *py_files* to the entry points plus everything they can import.

    Mirrors the resolution rules of the in-memory loader on the receiving side:
    only relative imports (``from .x import y``) resolve against the shipped
    set, so the closure follows ``ImportFrom`` nodes with ``level >= 1`` and
    ignores absolute imports (stdlib, third-party, or siblings that would not
    resolve anyway). ``__init__.py`` files of traversed sub-packages ride
    along; the top-level ``__init__.py`` never does, because the finder serves
    the root namespace as an empty package and its source is unreachable.
    Static analysis is sound here because ``analyze_code`` rejects dynamic
    imports (``importlib``, ``__import__``) in shipped code.

    Args:
        py_files: Dict mapping relative paths (forward slashes) to source text.
        entry_points: Keys whose import closure must be kept (the role files).
        forced: Keys included WITHOUT following their imports UNLESS some kept
            file also imports them (e.g. ``stats.py``: when only exec'd it runs
            in a bare module where relative imports cannot resolve, but a role
            file importing it turns it into a real namespace module whose
            dependencies must ship too).

    Returns:
        The filtered dict, preserving the iteration order of *py_files*.
    """
    kept: set[str] = set()
    enqueued: set[str] = set()
    queue: list[str] = []

    # Directory prefixes present in the tree: the loader auto-creates a namespace
    # package for each of them, so imports can legally target bare directories
    dir_prefixes: set[str] = set()
    for k in py_files:
        parts = k.split('/')
        for i in range(1, len(parts)):
            dir_prefixes.add('/'.join(parts[:i]))

    def _add(rel: str) -> None:
        if rel not in py_files:
            return
        if rel not in kept:
            kept.add(rel)
            # Sub-package __init__.py files ride along (never the root one)
            parts = rel.split('/')
            for i in range(1, len(parts)):
                _add('/'.join(parts[:i]) + '/__init__.py')
        if rel not in enqueued:
            enqueued.add(rel)
            queue.append(rel)

    def _add_subtree(prefix: str) -> None:
        # Conservative: everything under a package targeted as a whole (namespace
        # dirs, star-imports whose __all__ names submodules the AST cannot see)
        for k in py_files:
            if k.startswith(prefix + '/'):
                _add(k)

    for entry in entry_points:
        _add(entry)
    for name in forced:
        if name in py_files:
            kept.add(name)  # Not enqueued: traversed only if an import reaches it

    while queue:
        rel = queue.pop()
        try:
            tree = ast.parse(py_files[rel])
        except SyntaxError:
            continue  # Kept as-is; an unparsable file contributes no edges
        base = rel.split('/')[:-1]
        for node in ast.walk(tree):
            if not isinstance(node, ast.ImportFrom) or node.level < 1:
                continue
            if node.level - 1 > len(base):
                continue  # Escapes the shipped tree
            anchor = base[:len(base) - (node.level - 1)] if node.level > 1 else list(base)
            target = anchor + (node.module.split('.') if node.module else [])
            prefix = '/'.join(target)
            if node.module:
                _add(prefix + '.py')
                _add(prefix + '/__init__.py')
            for alias in node.names:
                if alias.name == '*':
                    if prefix in dir_prefixes:
                        _add_subtree(prefix)
                    continue
                leaf = (prefix + '/' if prefix else '') + alias.name
                _add(leaf + '.py')
                _add(leaf + '/__init__.py')
                if (leaf + '.py' not in py_files and leaf + '/__init__.py' not in py_files
                        and leaf in dir_prefixes):
                    _add_subtree(leaf)  # Bare namespace package (no __init__.py)

    return {k: v for k, v in py_files.items() if k in kept}

Returns the subset of py_files that the entry points reach through their imports and keeps the original order.

Argument Type Default Meaning
py_files dict[str, str] required Maps each path to its source in the format of collect_py_files.
entry_points list[str] required The paths to keep with everything they import (the files of the roles).
forced tuple[str, ...] () Paths kept unconditionally. Their own imports are followed only when a kept file imports them too. The world passes ("stats.py",).

The function follows only the relative imports (from .x import y, from ..pkg import *) because only these resolve against the shipped files on the receiving side. It parses the files statically with ast. A file with a syntax error is kept and contributes no import. The __init__.py files of the traversed subpackages are kept and the __init__.py at the root never is. A star import of a folder keeps the whole folder. The same holds for an import of a folder without __init__.py. AgentBasics calls it when it packs the roles of a world.

analyze_code

analyze_code(files_in_memory: dict[str, str]) -> bool
Source code in unaiverse/utils/misc.py
def analyze_code(files_in_memory: dict[str, str]) -> bool:
    """Analyzes a string of Python code for dangerous or unsafe functions and modules.

        Args:
            files_in_memory: The dict "file name to code string with contents".

        Returns:
            True if the code is considered safe, otherwise False.
        """

    dangerous_modules = {"subprocess", "ctypes", "pty", "socket", "pickle", "marshal", "importlib"}
    modules_with_dangerous_functions = {"os", "shutil", "sys", "signal"}
    dangerous_functions = {
        # Core Builtins / Code Execution
        "eval", "exec", "compile", "__import__", "input",

        # OS Commands & Process Execution (os, subprocess)
        "system", "popen", "subprocess.Popen", "subprocess.run", "subprocess.call",

        # The exec() Family
        "execl", "execle", "execlp", "execlpe",
        "execv", "execve", "execvp", "execvpe",

        # The spawn() Family
        "spawnl", "spawnle", "spawnlp", "spawnlpe",
        "spawnv", "spawnve", "spawnvp", "spawnvpe",
        "posix_spawn", "posix_spawnp",

        # Process Management
        "fork", "kill",

        # File System Destruction (os, shutil)
        "remove", "unlink", "rmdir", "removedirs", "rmtree"
    }

    def is_suspicious(ast_node):

        # Detect bare function calls like eval(...)
        if isinstance(ast_node, ast.Call):
            # case: eval(...)  (ast.Name)
            if isinstance(ast_node.func, ast.Name):
                return ast_node.func.id in dangerous_functions
            # case: something.eval(...)  (ast.Attribute)
            elif isinstance(ast_node.func, ast.Attribute):
                attr_name = ast_node.func.attr
                # 1) If attribute name is one of the dangerous_functions, only flag it
                #    if the object is a suspicious module (os, subprocess, etc.)
                if attr_name in dangerous_functions:
                    value = ast_node.func.value
                    # example: os.system(...)  => ast.Name(id='os')
                    if isinstance(value, ast.Name):
                        if value.id in dangerous_modules or value.id in modules_with_dangerous_functions:
                            return True
                    # example: package.subpackage.func(...) => ast.Attribute
                    # check top-level name if possible: walk down to the leftmost Name
                    left = value
                    while isinstance(left, ast.Attribute):
                        left = left.value
                    if isinstance(left, ast.Name) and (
                            left.id in dangerous_modules or left.id in modules_with_dangerous_functions):
                        return True
                # 2) Also catch explicit module imports used directly:
                #    subprocess.run(...), os.system(...), etc.
                if isinstance(ast_node.func.value, ast.Name):
                    if ast_node.func.value.id in dangerous_modules:
                        # if the module is suspicious, any attribute call is risky
                        return True

        # Detect imports
        if isinstance(ast_node, ast.Import):
            for alias in ast_node.names:
                if alias.name.split('.')[0] in dangerous_modules:
                    return True
        elif isinstance(ast_node, ast.ImportFrom):
            if ast_node.module and ast_node.module.split('.')[0] in dangerous_modules:
                return True

        return False

    for file_in_memory in files_in_memory.values():
        try:
            tree = ast.parse(file_in_memory)
        except SyntaxError:
            return False

        for _ast_node in ast.walk(tree):
            if is_suspicious(_ast_node):
                return False

    return True

Screens a set of source files for dangerous code and returns True when it finds none. The argument maps file names to source text. The node calls it on the code that a world sends before running any of it. In the current version this is the only check on that code.

The function parses each file with ast and returns False at the first match of these rules:

  1. A syntax error.
  2. An import of subprocess, ctypes, pty, socket, pickle, marshal or importlib, also as from ... import.
  3. A call of a bare name among eval, exec, compile, __import__, input, system, popen, fork, kill, remove, unlink, rmdir, removedirs, rmtree and the exec* and spawn* families of os.
  4. A call of one of those names as an attribute of os, shutil, sys, signal or of a module of rule 2 (for example os.system(...), shutil.rmtree(...)).
  5. Any call of an attribute of a module of rule 2.

It is a static list of names and not a sandbox. Code that reaches the same functions indirectly passes the check (for example getattr(os, "system")("..."), pathlib.Path(p).unlink() or open(p, "w")). The sandbox isolates code at run time.

InMemoryFinder

InMemoryFinder(py_files: dict[str, str], namespace: str)

Bases: MetaPathFinder

Source code in unaiverse/utils/misc.py
def __init__(self, py_files: dict[str, str], namespace: str) -> None:
    self._ns = namespace

    # fullname -> (source, virtual_path, is_package)
    self._mods: dict[str, tuple[str, str, bool]] = {}

    # Discover all directories that contain at least one .py file,
    # so we can auto-generate implicit namespace packages for them.
    dirs: set[str] = set()
    for rel in py_files:
        parts = rel.split('/')
        for depth in range(1, len(parts)):
            dirs.add('/'.join(parts[:depth]))

    for rel, source in py_files.items():
        parts = rel.split('/')
        filename = parts[-1]
        sub_dirs = parts[:-1]

        if filename == '__init__.py':
            mod_name = namespace + ('.' + '.'.join(sub_dirs) if sub_dirs else '')
            is_pkg = True
        else:
            stem = filename[:-3]  # strip .py
            mod_name = namespace + '.' + '.'.join(sub_dirs + [stem])
            is_pkg = False

        v_path = f'<world:{namespace}>/{rel}'
        self._mods[mod_name] = (source, v_path, is_pkg)

    # Auto-create empty namespace packages for directories with no __init__.py
    for d in dirs:
        pkg_name = namespace + '.' + d.replace('/', '.')
        if pkg_name not in self._mods:
            self._mods[pkg_name] = ('', f'<world:{namespace}>/{d}/__init__.py', True)

An import hook (an importlib.abc.MetaPathFinder) that serves modules from a dict of source files instead of the disk. Each instance owns a namespace (a unique top-level package name such as _dyn_3f2a9c1e). The roles of different worlds loaded in one process therefore never collide in sys.modules.

Argument Type Meaning
py_files dict[str, str] Maps each path to its source. "role1.py" becomes the module <namespace>.role1 and "utils/__init__.py" the package <namespace>.utils.
namespace str The top-level package name.

A folder without __init__.py becomes an empty package. Tracebacks show the source path of each module as <world:<namespace>>/<path>. The constructor does not register the finder. load_agent_in_memory inserts it at the head of sys.meta_path.

find_spec

find_spec(fullname: str, path: object, target: object = None) -> ModuleSpec | None
Source code in unaiverse/utils/misc.py
def find_spec(self, fullname: str, path: object, target: object = None) -> importlib.machinery.ModuleSpec | None:

    # Root namespace package
    if fullname == self._ns:
        spec = importlib.machinery.ModuleSpec(fullname, loader=None, origin=f'<world:{self._ns}>', is_package=True)
        spec.submodule_search_locations = []
        return spec

    if fullname not in self._mods:
        return None

    source, v_path, is_pkg = self._mods[fullname]
    loader = _InMemoryLoader(source, v_path)
    spec = importlib.machinery.ModuleSpec(fullname, loader, origin=v_path, is_package=is_pkg)
    if is_pkg:
        spec.submodule_search_locations = []
    return spec

The hook that the import system calls. It returns a ModuleSpec for the namespace package itself and for every module of the set. Any other name gives None. The method signature follows importlib.abc.MetaPathFinder.find_spec.

cleanup

cleanup() -> None
Source code in unaiverse/utils/misc.py
def cleanup(self) -> None:
    """Remove all owned modules from "sys.modules" and unregister this finder.

    Call this when the agent that was built from these sources is destroyed.
    """
    for name in list(self._mods):
        sys.modules.pop(name, None)
    sys.modules.pop(self._ns, None)
    try:
        sys.meta_path.remove(self)
    except ValueError:
        pass

Removes every module of the namespace (and the namespace itself) from sys.modules and removes the finder from sys.meta_path. Call it when the agent built from these sources is discarded.

load_agent_in_memory

load_agent_in_memory(py_files: dict[str, str], role: str, **init_kwargs: Any) -> tuple[Any, InMemoryFinder]
Source code in unaiverse/utils/misc.py
def load_agent_in_memory(py_files: dict[str, str], role: str, **init_kwargs: Any) -> tuple[Any, InMemoryFinder]:
    """Instantiate a ``WAgent`` from an in-memory Python source tree.

    The file ``{role}.py`` (at the root of *py_files*) is imported as the
    agent's main module.  Any ``import`` statements inside it are resolved
    against the other entries in *py_files* through a temporary
    ``InMemoryFinder`` registered on ``sys.meta_path``.

    Args:
        py_files: Dict mapping relative paths to source text (as produced by
            ``collect_py_files``).
        role: Role name; ``{role}.py`` is the entry-point module.
        **init_kwargs: Keyword arguments forwarded to ``WAgent.__init__``
            (e.g. ``proc=None``).

    Returns:
        A ``(agent_instance, finder)`` tuple.  The caller **must** keep
        *finder* alive as long as the agent is in use, and call
        ``finder.cleanup()`` when the agent is destroyed.

    Raises:
        KeyError: If ``{role}.py`` is not present in *py_files*.
        Exception: Any exception raised during module execution or
            ``WAgent.__init__``.
    """
    if f'{role}.py' not in py_files:
        raise GenException(f"No source file '{role}.py' found in the received module set "
                           f"(available: {list(py_files)})")

    namespace = f'_dyn_{_uuid.uuid4().hex[:8]}'
    finder = InMemoryFinder(py_files, namespace)
    sys.meta_path.insert(0, finder)  # insert first so it wins over real filesystem

    try:
        mod = importlib.import_module(f'{namespace}.{role}')
        agent = mod.WAgent(**init_kwargs)
    except Exception:
        finder.cleanup()
        raise

    return agent, finder

Imports <role>.py from py_files, creates agent = WAgent(**init_kwargs) from the class WAgent defined in that file and returns (agent, finder). The function creates an InMemoryFinder with a fresh namespace and inserts it first in sys.meta_path. The relative imports of the role therefore resolve against the other files of the set. The caller must keep finder as long as the agent lives and call finder.cleanup() afterwards.

A set without <role>.py raises GenException. An exception during the import or in WAgent.__init__ (an AttributeError when the file has no WAgent) removes the finder and propagates. AgentBasics calls it with proc=None to check the roles of a world and Node calls it to build the agent of the role that it receives when it joins a world.

from unaiverse.utils.misc import collect_py_files, load_agent_in_memory

files = collect_py_files("worlds/animal_school/src")
agent, finder = load_agent_in_memory(files, "student", proc=None)
# ... use the agent ...
finder.cleanup()

world_definition_members

world_definition_members(agent_files: dict[str, str], roles_fsm: dict[str, str]) -> dict[str, bytes]
Source code in unaiverse/utils/misc.py
def world_definition_members(agent_files: dict[str, str], roles_fsm: dict[str, str]) -> dict[str, bytes]:
    """Canonical member set of a world definition.

    ``code/<path>`` for every shipped source file (stats.py included) and
    ``fsm/<role>.json`` for every role FSM. The same member layout the root
    server reads from a declared GitHub commit, and the one the joiner-side
    check folds from the grant bundle, so all ends fold exactly the same bytes.

    Args:
        agent_files: Dict mapping relative paths to source text (the bundle).
        roles_fsm: Dict mapping role names to their FSM as a JSON string.

    Returns:
        Dict mapping canonical member names to their content bytes.
    """
    members = {f"code/{rel}": src.encode('utf-8') for rel, src in agent_files.items()}
    members |= {f"fsm/{role}.json": fsm.encode('utf-8') for role, fsm in roles_fsm.items()}
    return members

Returns a dict from the name of each canonical member of the definition of a world to its content encoded in UTF-8. The members are code/<path> for every source file of agent_files and fsm/<role>.json for the behavior (a JSON string) of every role in roles_fsm.

canonical_world_hash

canonical_world_hash(members: dict[str, bytes]) -> str
Source code in unaiverse/utils/misc.py
def canonical_world_hash(members: dict[str, bytes]) -> str:
    """Deterministic BLAKE2b (256-bit) digest of a world-definition member set.

    Members are folded in alphabetical order as ``<name>\\x00<content>``, the
    same folding the root server applies to the bundle it reads from a world's
    declared repository, so a joiner can recompute the attested hash from the
    grant bundle without ever touching the repository.

    Args:
        members: Dict mapping member names to content bytes.

    Returns:
        A 64-character lowercase hex digest.
    """
    h = hashlib.blake2b(digest_size=32)
    for name in sorted(members):
        h.update(name.encode('utf-8'))
        h.update(b'\x00')
        h.update(members[name])
    return h.hexdigest()

Returns the BLAKE2b digest (32 bytes, 64 lowercase hexadecimal characters) of a set of members. The function feeds each member to the hash as <name> \x00 <content> in alphabetical order of name. Two sets with the same names and contents always give the same hash. In the current version the node does not call this function or world_definition_members because the check of the code of a world against the hash attested by the root server is commented out.

Policy filters

A policy filter revises the action that the policy of a behavior has just chosen. An agent receives it as the argument policy_filter (world behavior) or policy_filter_lone_wolf (public behavior). The behavior calls it as filter(action_id, request, all_actions, policy_filter_opts) and runs nothing on that tick when it returns (-1, None). policy_filter_opts is a dict owned by the behavior that the filter uses to keep its state between calls. The two filters below hold back the actions whose name is in action_names and let every other action through.

PolicyFilterDelayAction

PolicyFilterDelayAction(action_names: set[str], wait: float, add_random_up_to: float = 0.0)
Source code in unaiverse/utils/misc.py
def __init__(self, action_names: set[str], wait: float, add_random_up_to: float = 0.) -> None:
    """Initializes the PolicyFilterSelfGen.

    Args:
        action_names: The name of the actions to delay (set).
        wait: Minimum number of seconds to wait before allowing ``action_name`` action to proceed.
        add_random_up_to: Upper bound of an additional random delay in seconds
            added to ``wait`` (default: 0.0; negative values are clamped to 0.0).

    Raises:
        GenException: If ``wait`` is not greater than zero.
    """
    self.action_names = action_names
    self.wait = wait
    self.add_random_up_to = max(add_random_up_to, 0.)
    if wait <= 0.:
        raise GenException("Invalid number of seconds ('wait' must be > 0)")

Delays the listed actions by a fixed time plus a random part.

Argument Type Default Meaning
action_names set[str] required The names of the actions to delay (for example {"process"}).
wait float required The minimum delay in seconds. A value <= 0 raises GenException.
add_random_up_to float 0.0 The upper bound of a uniform random delay added to wait. Negative values count as 0.

The first time the policy picks a listed action the filter records the time and draws the random part. Until wait plus that part has passed it returns (-1, None). Afterwards it lets the action through and resets. The clock keeps running when the policy picks other actions in between.

from unaiverse.agent import Agent
from unaiverse.utils.misc import PolicyFilterDelayAction

agent = Agent(proc=my_model, policy_filter=PolicyFilterDelayAction({"process"}, wait=1.0, add_random_up_to=1.0))

PolicyHumanLikeDelay

PolicyHumanLikeDelay(action_names: set[str], median_delay: float = 5.0, variability: float = 0.6)
Source code in unaiverse/utils/misc.py
def __init__(self, action_names: set[str], median_delay: float = 5.0, variability: float = 0.6) -> None:
    """Initializes the PolicyHumanLikeDelay.

    Args:
        action_names: The name of the actions to delay (set).
        median_delay: Median delay in seconds (the "typical" human response time).
        variability: How spread out the delays are (0.0 = nearly constant,
            1.0+ = very erratic). Values around 0.4-0.8 are realistic.
            Also controls momentum strength and distraction probability internally.

    Raises:
        GenException: If ``median_delay`` is not greater than zero.
    """
    if median_delay <= 0.:
        raise GenException("Invalid median_delay (must be > 0)")
    self.action_names = action_names
    self._mu = math.log(median_delay)
    self._sigma = max(variability, 0.)
    # Derived internals: momentum blends prev delay into the next one (more variability = more momentum)
    self._momentum = min(self._sigma * 0.4, 0.6)
    # Distraction: rare long pauses (probability scales with variability)
    self._distraction_prob = min(self._sigma * 0.08, 0.12)
    self._distraction_mult = 2.0 + self._sigma

Delays the listed actions by times that resemble the reaction times of a person.

Argument Type Default Meaning
action_names set[str] required The names of the actions to delay.
median_delay float 5.0 The median delay in seconds. A value <= 0 raises GenException.
variability float 0.6 The spread sigma of the delays (negative values count as 0). Values between 0.4 and 0.8 look realistic.

Each delay is drawn from a log-normal distribution with median median_delay and parameter sigma. It is then mixed with the previous delay with weight min(0.4 · sigma, 0.6) so that fast and slow answers come in runs. With probability min(0.08 · sigma, 0.12) it is multiplied by 2 + sigma to imitate a distraction. The filter draws the delay the first time the policy picks a listed action, returns (-1, None) until it has passed and then lets the action through.

Terminal and file utilities

Silent

Silent(ignore: bool = False)
Source code in unaiverse/utils/misc.py
def __init__(self, ignore: bool = False) -> None:
    """Initializes the Silent context manager.

    Args:
        ignore: If True, stdout is not suppressed (context manager is a no-op; default: False).
    """
    self.ignore = ignore

A context manager that sends sys.stdout to os.devnull and restores it on exit. ignore=True makes it do nothing. Standard error and the output of native code still reach the terminal because native code writes to the file descriptor directly.

countdown_start

countdown_start(seconds: int, msg: str) -> Thread
Source code in unaiverse/utils/misc.py
def countdown_start(seconds: int, msg: str) -> threading.Thread:
    """Starts a tqdm progress-bar countdown in a background thread.

    Args:
        seconds: Number of seconds to count down.
        msg: Description label displayed next to the progress bar.

    Returns:
        The background ``threading.Thread`` running the countdown.
    """
    class TqdmPrintRedirector:
        def __init__(self, tqdm_instance: tqdm) -> None:
            self.tqdm_instance = tqdm_instance
            self.original_stdout = sys.__stdout__

        def write(self, s: str) -> None:
            if s.strip():  # Ignore empty lines (needed for the way tqdm works)
                self.tqdm_instance.write(s, file=self.original_stdout)

        def flush(self) -> None:
            pass  # Tqdm handles flushing

    def drawing(secs: int, message: str) -> None:
        saved_stdout = sys.stdout  # whatever was active, not sys.__stdout__
        try:
            with tqdm(total=secs, desc=message, file=sys.__stdout__) as t:
                sys.stdout = TqdmPrintRedirector(t)  # Redirect prints to tqdm.write
                for i in range(secs):
                    time.sleep(1)
                    t.update(1.)
        finally:
            sys.stdout = saved_stdout  # Restore the prior value, always

    sys.stdout.flush()
    handle = threading.Thread(target=drawing, args=(seconds, msg))
    handle.start()
    return handle

Starts a thread that draws a tqdm progress bar of seconds steps of one second labeled msg and returns the thread. While the bar runs, the print calls of the whole process go through tqdm.write and appear above the bar. The thread is not a daemon and the process waits for it at exit.

countdown_wait

countdown_wait(handle: Thread) -> None
Source code in unaiverse/utils/misc.py
def countdown_wait(handle: threading.Thread) -> None:
    """Blocks until the countdown thread created by ``countdown_start`` finishes.

    Args:
        handle: The thread handle returned by ``countdown_start``.
    """
    handle.join()

Waits for the thread returned by countdown_start.

check_json_start

check_json_start(file: str, msg: str, delete_existing: bool = False) -> Thread
Source code in unaiverse/utils/misc.py
def check_json_start(file: str, msg: str, delete_existing: bool = False) -> threading.Thread:
    """Starts a background daemon thread that monitors a JSON file for changes and pretty-prints it.

    Args:
        file: Path to the JSON file to monitor.
        msg: A header message printed once when monitoring begins.
        delete_existing: If True, removes the file before starting the monitor (default: False).

    Returns:
        The daemon ``threading.Thread`` running the file-watcher loop.
    """
    from rich.json import JSON
    from rich.console import Console
    cons = Console(file=sys.__stdout__)

    if delete_existing:
        if os.path.exists(file):
            os.remove(file)

    def checking(file_path: str, console: Console):
        print(msg)
        prev_dict = {}
        while True:
            if os.path.exists(file_path):
                try:
                    with open(file_path, "r", encoding='utf-8') as f:
                        json_dict = json.load(f)
                        if json_dict != prev_dict:
                            now = datetime.now()
                            console.print("─" * 80)
                            console.print("Printing updated file "
                                          "(print time: " + now.strftime("%Y-%m-%d %H:%M:%S") + ")")
                            console.print("─" * 80)
                            console.print(JSON.from_data(json_dict))
                        prev_dict = json_dict
                except KeyboardInterrupt:
                    break
                except Exception:
                    pass
            time.sleep(1)

    handle = threading.Thread(target=checking, args=(file, cons), daemon=True)
    handle.start()
    return handle

Starts a daemon thread that prints msg and then checks the JSON file file every second. Whenever its content changes the thread prints it with rich. That package is not a declared dependency of the SDK. delete_existing=True deletes the file before the start. The function returns the thread. The thread never ends by itself.

check_json_start_wait

check_json_start_wait(handle: Thread) -> None
Source code in unaiverse/utils/misc.py
def check_json_start_wait(handle: threading.Thread) -> None:
    """Blocks until the JSON-watcher thread created by ``check_json_start`` finishes.

    Args:
        handle: The thread handle returned by ``check_json_start``.
    """
    handle.join()

Waits for the thread returned by check_json_start. Because that thread runs forever, the call blocks until the process is interrupted.

show_images_grid

show_images_grid(image_paths: list[str], max_cols: int = 3) -> None
Source code in unaiverse/utils/misc.py
def show_images_grid(image_paths: list[str], max_cols: int = 3) -> None:
    """Displays a grid of images from the given file paths using matplotlib.

    Args:
        image_paths: A list of file-path strings pointing to the images to display.
        max_cols: Maximum number of columns in the grid (default: 3).
    """
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg

    n = len(image_paths)
    cols = min(max_cols, n)
    rows = math.ceil(n / cols)

    # Load images
    images = [mpimg.imread(p) for p in image_paths]

    # Determine figure size based on image sizes
    widths, heights = zip(*[(img.shape[1], img.shape[0]) for img in images])

    # Use average width/height for scaling
    avg_width = float(sum(widths)) / len(widths)
    avg_height = float(sum(heights)) / len(heights)

    fig_width = cols * avg_width / 100
    fig_height = rows * avg_height / 100

    fig, axes = plt.subplots(rows, cols, figsize=(fig_width, fig_height))
    axes = axes.flatten() if n > 1 else [axes]

    assert fig.canvas.manager is not None
    fig.canvas.manager.set_window_title("Image Grid")

    # Hide unused axes
    for ax in axes[n:]:
        ax.axis('off')

    for idx, (ax, img) in enumerate(zip(axes, images)):
        ax.imshow(img)
        ax.axis('off')
        ax.set_title(str(idx), fontsize=12, fontweight='bold')

    plt.subplots_adjust(wspace=0, hspace=0)

    # Turn on interactive mode
    plt.ion()
    plt.show()

    fig.canvas.draw()
    plt.pause(0.1)

Opens a non-blocking matplotlib window titled Image Grid with the pictures of image_paths on a grid of at most max_cols columns (default 3). Each picture shows its index as title. The figure size follows the average size of the pictures at 100 pixels per inch. matplotlib is not a declared dependency of the SDK. ImageFileStream calls it when show_images=True.

FileTracker

FileTracker(folder: str, ext: str = '.json', prefix: str | None = None, skip: str | None = None)
Source code in unaiverse/utils/misc.py
def __init__(self, folder: str, ext: str = ".json",
             prefix: str | None = None, skip: str | None = None) -> None:
    """Initializes the FileTracker and takes an initial snapshot of the folder.

    Args:
        folder: Path to the folder to monitor.
        ext: File extension to watch (default: ".json").
        prefix: If set, only files whose names start with this prefix are tracked (default: None).
        skip: If set, files with this exact name are ignored (default: None).
    """
    self.folder = Path(folder)
    self.ext = ext.lower()
    self.skip = skip
    self.prefix = prefix
    self.last_state = self.__scan_files()

Watches the files of one folder for creation, change and deletion.

Argument Type Default Meaning
folder str required The folder. Subfolders are not scanned.
ext str ".json" The extension of the watched files. The comparison ignores case.
prefix str or None None When given, only the files whose name starts with it are watched.
skip str or None None A file name to ignore.

The constructor takes a first snapshot with the MD5 hash of the content of every watched file. A change of content counts while a new modification time alone does not. AgentBasics uses it to notice edits to the behavior files of a world folder.

something_changed

something_changed() -> bool
Source code in unaiverse/utils/misc.py
def something_changed(self) -> bool:
    """Checks whether any tracked file has been created, modified, or deleted since the last call.

    Updates the internal snapshot on every call.

    Returns:
        True if at least one file changed, False otherwise.
    """
    new_state = self.__scan_files()

    created = [f for f in new_state if f not in self.last_state]
    modified = [f for f in new_state if f in self.last_state and new_state[f] != self.last_state[f]]
    deleted = [f for f in self.last_state if f not in new_state]  # Track deletions

    has_changed = bool(created or modified or deleted)
    self.last_state = new_state
    return has_changed

Takes a new snapshot and returns True when a watched file appeared, changed content or disappeared since the previous snapshot. The new snapshot replaces the old one in every case.

Bounded dict

MultiPartLimitedDict

MultiPartLimitedDict(part_name_to_limit: dict)

Bases: dict

Source code in unaiverse/utils/misc.py
def __init__(self, part_name_to_limit: dict) -> None:
    """Initializes the MultiPartLimitedDict.

    Args:
        part_name_to_limit: A dictionary mapping partition names to their maximum entry counts.
    """
    super().__init__()
    self._limits = part_name_to_limit
    self._trackers = {k: deque() for k in part_name_to_limit}
    self._current_part = next(iter(part_name_to_limit.keys()))  # Default part

A dict whose keys belong to named partitions, each with a maximum number of keys. part_name_to_limit maps each partition name to its limit (for example {"recent": 100, "pinned": 10}). The first partition is the initial current partition. An empty mapping raises StopIteration.

An assignment d[key] = value adds the key to the current partition as its newest entry. When the partition exceeds its limit its oldest key is deleted from the dict even when another partition tracks the same key. Only item assignment updates the partitions. update, setdefault and del bypass them and del leaves the key tracked.

set_part

set_part(part_label: str) -> None
Source code in unaiverse/utils/misc.py
def set_part(self, part_label: str) -> None:
    """Switches the active partition so that subsequent ``__setitem__`` calls are attributed to it.

    Args:
        part_label: The name of the partition to activate.  Unknown labels are silently ignored.
    """
    if part_label in self._limits:
        self._current_part = part_label

Makes part_label the current partition for the next assignments. An unknown label is ignored.