A collection of helpers that the node, the agent and the scripts of the examples share. They fall into six groups:
Identity and keys: the public handle of an account, the identifier of a node and the UNaIVERSE key.
Addresses: saving and reading the network addresses of running nodes.
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).
Policy filters that delay the actions of an agent (see Behaviors).
Terminal and file utilities: silencing output, a countdown, watching a JSON file or a folder, showing pictures.
MultiPartLimitedDict, a dict with bounded partitions.
defowner_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)."""returnstatic_profile.get('nickname')orstatic_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.
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.
defget_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 keytry:key_dir=prepare_app_dir(app_name="UNaIVERSE")exceptException:raiseGenException("Cannot create folder to store the key file")key_file=os.path.join(key_dir,"key")# Getting from an existing filekey_from_file=Noneifos.path.exists(key_file):withopen(key_file,"r")asf:key_from_file=f.read().strip()# Getting from env variablekey_from_env=os.getenv("NODE_KEY",None)# Getting from code-specified optionifkey_variableisnotNoneandlen(key_variable.strip())>0:key_from_var=key_variable.strip()ifkey_from_var.startswith("<")andkey_from_var.endswith(">"):# Something like <UNAIVERSE_KEY_GOES_HERE>key_from_var=Noneelse: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=Falsemultiple_source=Falsefirst_key=Nonefirst_source=None_prev_key=Nonefori,(_key,_source_name)inenumerate(zip(_keys,_source_names)):if_keyisnotNone:source_names.append(_source_name)if_prev_keyisnotNone:if_key!=_prev_key:mismatching=Truemultiple_source=True_prev_key=_keyelse:_prev_key=_keyfirst_key=_keyfirst_source=_source_nameiflen(source_names)>0:ifmultiple_sourceandnotmismatching:msg="UNaIVERSE key (the exact same key) present in multiple locations: "+", ".join(source_names)print(msg)ifmultiple_sourceandmismatching:assertisinstance(first_source,str)msg="UNaIVERSE keys (different keys) present in multiple locations: "+", ".join(source_names)msg+="\nLoaded the one stored in "+first_sourceprint(msg)# if not multiple_source:# msg = f"UNaIVERSE key loaded from {first_source}"# print(msg)assertisinstance(first_key,str)returnfirst_keyelse:# If no key present, ask user and save to fileprint("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()withopen(key_file,"w")asf:f.write(key)returnkey
Returns the UNaIVERSE key of the user. The function looks at three sources in this order and returns the first one found:
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.
The environment variable NODE_KEY.
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.
defprepare_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()ifos.name=="nt":# Windowsifos.getenv("APPDATA")isnotNone:key_dir=os.path.join(str(os.getenv("APPDATA")),"Local",app_name)# Expectedelse:key_dir=os.path.join(str(Path.home()),f".{app_name}")# Fallbackelse:# Linux/macOSkey_dir=os.path.join(str(Path.home()),f".{app_name}")os.makedirs(key_dir,exist_ok=True)returnkey_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.
defsave_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)withopen(address_file,"w"ifnotappendelse"a")asfile:file.write(node.hosted.get_name()+";"+str(node.get_public_addresses()ifpublicelsenode.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.
defget_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={}withopen(os.path.join(dir_path,filename))asfile:lines=file.readlines()ifnotlinesorlen(lines)==0:returnret# Old file formatiflines[0].strip()=="/":addresses=[]forlineinlines:_line=line.strip()iflen(_line)>0:addresses.append(_line)ret["unk"]=addressesreturnret# New file formatforlineinlines:ifline.strip().startswith("***"):# Header markercontinuecomma_separated_values=[v.strip()forvinline.split(';')]node_name,addresses_str=comma_separated_valuesret[node_name]=ast.literal_eval(addresses_str)# Name appearing multiple times? the last entry is keptreturnret
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.
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.
defcollect_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. """ifexclude_dirsisNone:exclude_dirs=set()root=Path(folder)result:dict[str,str]={}forpy_fileinroot.rglob('*.py'):rel=py_file.relative_to(root)ifany(partinexclude_dirsforpartinrel.parts[:-1]):continuefile_name_with_relative_path=str(rel).replace('\\','/')result[file_name_with_relative_path]=py_file.read_text(encoding='utf-8')returnresult
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.
defpack_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')returnbase64.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.
defunpack_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. """returnjson.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.
defprune_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 directoriesdir_prefixes:set[str]=set()forkinpy_files:parts=k.split('/')foriinrange(1,len(parts)):dir_prefixes.add('/'.join(parts[:i]))def_add(rel:str)->None:ifrelnotinpy_files:returnifrelnotinkept:kept.add(rel)# Sub-package __init__.py files ride along (never the root one)parts=rel.split('/')foriinrange(1,len(parts)):_add('/'.join(parts[:i])+'/__init__.py')ifrelnotinenqueued: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)forkinpy_files:ifk.startswith(prefix+'/'):_add(k)forentryinentry_points:_add(entry)fornameinforced:ifnameinpy_files:kept.add(name)# Not enqueued: traversed only if an import reaches itwhilequeue:rel=queue.pop()try:tree=ast.parse(py_files[rel])exceptSyntaxError:continue# Kept as-is; an unparsable file contributes no edgesbase=rel.split('/')[:-1]fornodeinast.walk(tree):ifnotisinstance(node,ast.ImportFrom)ornode.level<1:continueifnode.level-1>len(base):continue# Escapes the shipped treeanchor=base[:len(base)-(node.level-1)]ifnode.level>1elselist(base)target=anchor+(node.module.split('.')ifnode.moduleelse[])prefix='/'.join(target)ifnode.module:_add(prefix+'.py')_add(prefix+'/__init__.py')foraliasinnode.names:ifalias.name=='*':ifprefixindir_prefixes:_add_subtree(prefix)continueleaf=(prefix+'/'ifprefixelse'')+alias.name_add(leaf+'.py')_add(leaf+'/__init__.py')if(leaf+'.py'notinpy_filesandleaf+'/__init__.py'notinpy_filesandleafindir_prefixes):_add_subtree(leaf)# Bare namespace package (no __init__.py)return{k:vfork,vinpy_files.items()ifkinkept}
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.
defanalyze_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"}defis_suspicious(ast_node):# Detect bare function calls like eval(...)ifisinstance(ast_node,ast.Call):# case: eval(...) (ast.Name)ifisinstance(ast_node.func,ast.Name):returnast_node.func.idindangerous_functions# case: something.eval(...) (ast.Attribute)elifisinstance(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.)ifattr_nameindangerous_functions:value=ast_node.func.value# example: os.system(...) => ast.Name(id='os')ifisinstance(value,ast.Name):ifvalue.idindangerous_modulesorvalue.idinmodules_with_dangerous_functions:returnTrue# example: package.subpackage.func(...) => ast.Attribute# check top-level name if possible: walk down to the leftmost Nameleft=valuewhileisinstance(left,ast.Attribute):left=left.valueifisinstance(left,ast.Name)and(left.idindangerous_modulesorleft.idinmodules_with_dangerous_functions):returnTrue# 2) Also catch explicit module imports used directly:# subprocess.run(...), os.system(...), etc.ifisinstance(ast_node.func.value,ast.Name):ifast_node.func.value.idindangerous_modules:# if the module is suspicious, any attribute call is riskyreturnTrue# Detect importsifisinstance(ast_node,ast.Import):foraliasinast_node.names:ifalias.name.split('.')[0]indangerous_modules:returnTrueelifisinstance(ast_node,ast.ImportFrom):ifast_node.moduleandast_node.module.split('.')[0]indangerous_modules:returnTruereturnFalseforfile_in_memoryinfiles_in_memory.values():try:tree=ast.parse(file_in_memory)exceptSyntaxError:returnFalsefor_ast_nodeinast.walk(tree):ifis_suspicious(_ast_node):returnFalsereturnTrue
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:
A syntax error.
An import of subprocess, ctypes, pty, socket, pickle, marshal or importlib, also as from ... import.
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.
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(...)).
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.
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()forrelinpy_files:parts=rel.split('/')fordepthinrange(1,len(parts)):dirs.add('/'.join(parts[:depth]))forrel,sourceinpy_files.items():parts=rel.split('/')filename=parts[-1]sub_dirs=parts[:-1]iffilename=='__init__.py':mod_name=namespace+('.'+'.'.join(sub_dirs)ifsub_dirselse'')is_pkg=Trueelse:stem=filename[:-3]# strip .pymod_name=namespace+'.'+'.'.join(sub_dirs+[stem])is_pkg=Falsev_path=f'<world:{namespace}>/{rel}'self._mods[mod_name]=(source,v_path,is_pkg)# Auto-create empty namespace packages for directories with no __init__.pyfordindirs:pkg_name=namespace+'.'+d.replace('/','.')ifpkg_namenotinself._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.
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.
defcleanup(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. """fornameinlist(self._mods):sys.modules.pop(name,None)sys.modules.pop(self._ns,None)try:sys.meta_path.remove(self)exceptValueError: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.
defload_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__``. """iff'{role}.py'notinpy_files:raiseGenException(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 filesystemtry:mod=importlib.import_module(f'{namespace}.{role}')agent=mod.WAgent(**init_kwargs)exceptException:finder.cleanup()raisereturnagent,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.
fromunaiverse.utils.miscimportcollect_py_files,load_agent_in_memoryfiles=collect_py_files("worlds/animal_school/src")agent,finder=load_agent_in_memory(files,"student",proc=None)# ... use the agent ...finder.cleanup()
defworld_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')forrel,srcinagent_files.items()}members|={f"fsm/{role}.json":fsm.encode('utf-8')forrole,fsminroles_fsm.items()}returnmembers
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.
defcanonical_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)fornameinsorted(members):h.update(name.encode('utf-8'))h.update(b'\x00')h.update(members[name])returnh.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.
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.
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_namesself.wait=waitself.add_random_up_to=max(add_random_up_to,0.)ifwait<=0.:raiseGenException("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.
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. """ifmedian_delay<=0.:raiseGenException("Invalid median_delay (must be > 0)")self.action_names=action_namesself._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.
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.
defcountdown_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. """classTqdmPrintRedirector:def__init__(self,tqdm_instance:tqdm)->None:self.tqdm_instance=tqdm_instanceself.original_stdout=sys.__stdout__defwrite(self,s:str)->None:ifs.strip():# Ignore empty lines (needed for the way tqdm works)self.tqdm_instance.write(s,file=self.original_stdout)defflush(self)->None:pass# Tqdm handles flushingdefdrawing(secs:int,message:str)->None:saved_stdout=sys.stdout# whatever was active, not sys.__stdout__try:withtqdm(total=secs,desc=message,file=sys.__stdout__)ast:sys.stdout=TqdmPrintRedirector(t)# Redirect prints to tqdm.writeforiinrange(secs):time.sleep(1)t.update(1.)finally:sys.stdout=saved_stdout# Restore the prior value, alwayssys.stdout.flush()handle=threading.Thread(target=drawing,args=(seconds,msg))handle.start()returnhandle
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.
defcountdown_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()
defcheck_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. """fromrich.jsonimportJSONfromrich.consoleimportConsolecons=Console(file=sys.__stdout__)ifdelete_existing:ifos.path.exists(file):os.remove(file)defchecking(file_path:str,console:Console):print(msg)prev_dict={}whileTrue:ifos.path.exists(file_path):try:withopen(file_path,"r",encoding='utf-8')asf:json_dict=json.load(f)ifjson_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_dictexceptKeyboardInterrupt:breakexceptException:passtime.sleep(1)handle=threading.Thread(target=checking,args=(file,cons),daemon=True)handle.start()returnhandle
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.
defcheck_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.
defshow_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). """importmatplotlib.pyplotaspltimportmatplotlib.imageasmpimgn=len(image_paths)cols=min(max_cols,n)rows=math.ceil(n/cols)# Load imagesimages=[mpimg.imread(p)forpinimage_paths]# Determine figure size based on image sizeswidths,heights=zip(*[(img.shape[1],img.shape[0])forimginimages])# Use average width/height for scalingavg_width=float(sum(widths))/len(widths)avg_height=float(sum(heights))/len(heights)fig_width=cols*avg_width/100fig_height=rows*avg_height/100fig,axes=plt.subplots(rows,cols,figsize=(fig_width,fig_height))axes=axes.flatten()ifn>1else[axes]assertfig.canvas.managerisnotNonefig.canvas.manager.set_window_title("Image Grid")# Hide unused axesforaxinaxes[n:]:ax.axis('off')foridx,(ax,img)inenumerate(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 modeplt.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.
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=skipself.prefix=prefixself.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.
defsomething_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=[fforfinnew_stateiffnotinself.last_state]modified=[fforfinnew_stateiffinself.last_stateandnew_state[f]!=self.last_state[f]]deleted=[fforfinself.last_stateiffnotinnew_state]# Track deletionshas_changed=bool(createdormodifiedordeleted)self.last_state=new_statereturnhas_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.
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_limitself._trackers={k:deque()forkinpart_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.
defset_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. """ifpart_labelinself._limits:self._current_part=part_label
Makes part_label the current partition for the next assignments. An unknown label is ignored.