unaiverse 0.1.8__cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of unaiverse might be problematic. Click here for more details.

Files changed (50) hide show
  1. unaiverse/__init__.py +19 -0
  2. unaiverse/agent.py +2008 -0
  3. unaiverse/agent_basics.py +2041 -0
  4. unaiverse/clock.py +191 -0
  5. unaiverse/dataprops.py +1209 -0
  6. unaiverse/hsm.py +1889 -0
  7. unaiverse/modules/__init__.py +18 -0
  8. unaiverse/modules/cnu/__init__.py +17 -0
  9. unaiverse/modules/cnu/cnus.py +536 -0
  10. unaiverse/modules/cnu/layers.py +261 -0
  11. unaiverse/modules/cnu/psi.py +60 -0
  12. unaiverse/modules/hl/__init__.py +15 -0
  13. unaiverse/modules/hl/hl_utils.py +411 -0
  14. unaiverse/modules/networks.py +1509 -0
  15. unaiverse/modules/utils.py +710 -0
  16. unaiverse/networking/__init__.py +16 -0
  17. unaiverse/networking/node/__init__.py +18 -0
  18. unaiverse/networking/node/connpool.py +1261 -0
  19. unaiverse/networking/node/node.py +2299 -0
  20. unaiverse/networking/node/profile.py +447 -0
  21. unaiverse/networking/node/tokens.py +79 -0
  22. unaiverse/networking/p2p/__init__.py +188 -0
  23. unaiverse/networking/p2p/go.mod +127 -0
  24. unaiverse/networking/p2p/go.sum +548 -0
  25. unaiverse/networking/p2p/golibp2p.py +18 -0
  26. unaiverse/networking/p2p/golibp2p.pyi +135 -0
  27. unaiverse/networking/p2p/lib.go +2527 -0
  28. unaiverse/networking/p2p/lib.go.sha256 +1 -0
  29. unaiverse/networking/p2p/lib_types.py +312 -0
  30. unaiverse/networking/p2p/message_pb2.py +63 -0
  31. unaiverse/networking/p2p/messages.py +268 -0
  32. unaiverse/networking/p2p/mylogger.py +77 -0
  33. unaiverse/networking/p2p/p2p.py +929 -0
  34. unaiverse/networking/p2p/proto-go/message.pb.go +616 -0
  35. unaiverse/networking/p2p/unailib.cpython-312-aarch64-linux-gnu.so +0 -0
  36. unaiverse/streamlib/__init__.py +15 -0
  37. unaiverse/streamlib/streamlib.py +210 -0
  38. unaiverse/streams.py +770 -0
  39. unaiverse/utils/__init__.py +16 -0
  40. unaiverse/utils/ask_lone_wolf.json +27 -0
  41. unaiverse/utils/lone_wolf.json +19 -0
  42. unaiverse/utils/misc.py +492 -0
  43. unaiverse/utils/sandbox.py +293 -0
  44. unaiverse/utils/server.py +435 -0
  45. unaiverse/world.py +353 -0
  46. unaiverse-0.1.8.dist-info/METADATA +365 -0
  47. unaiverse-0.1.8.dist-info/RECORD +50 -0
  48. unaiverse-0.1.8.dist-info/WHEEL +7 -0
  49. unaiverse-0.1.8.dist-info/licenses/LICENSE +43 -0
  50. unaiverse-0.1.8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2299 @@
1
+ """
2
+ █████ █████ ██████ █████ █████ █████ █████ ██████████ ███████████ █████████ ██████████
3
+ ░░███ ░░███ ░░██████ ░░███ ░░███ ░░███ ░░███ ░░███░░░░░█░░███░░░░░███ ███░░░░░███░░███░░░░░█
4
+ ░███ ░███ ░███░███ ░███ ██████ ░███ ░███ ░███ ░███ █ ░ ░███ ░███ ░███ ░░░ ░███ █ ░
5
+ ░███ ░███ ░███░░███░███ ░░░░░███ ░███ ░███ ░███ ░██████ ░██████████ ░░█████████ ░██████
6
+ ░███ ░███ ░███ ░░██████ ███████ ░███ ░░███ ███ ░███░░█ ░███░░░░░███ ░░░░░░░░███ ░███░░█
7
+ ░███ ░███ ░███ ░░█████ ███░░███ ░███ ░░░█████░ ░███ ░ █ ░███ ░███ ███ ░███ ░███ ░ █
8
+ ░░████████ █████ ░░█████░░████████ █████ ░░███ ██████████ █████ █████░░█████████ ██████████
9
+ ░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░░ ░░░ ░░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░░ ░░░░░░░░░░
10
+ A Collectionless AI Project (https://collectionless.ai)
11
+ Registration/Login: https://unaiverse.io
12
+ Code Repositories: https://github.com/collectionlessai/
13
+ Main Developers: Stefano Melacci (Project Leader), Christian Di Maio, Tommaso Guidi
14
+ """
15
+ import os
16
+ import sys
17
+ import ast
18
+ import cv2
19
+ import copy
20
+ import json
21
+ import math
22
+ import time
23
+ import html
24
+ import queue
25
+ import types
26
+ import requests
27
+ import threading
28
+ import traceback
29
+ from PIL import Image
30
+ from typing import Optional
31
+ from collections import deque
32
+ from unaiverse.clock import Clock
33
+ from unaiverse.world import World
34
+ from unaiverse.agent import Agent
35
+ from unaiverse.networking.p2p import P2P, P2PError
36
+ from unaiverse.networking.p2p.messages import Msg
37
+ from datetime import datetime, timezone, timedelta
38
+ from unaiverse.networking.node.connpool import NodeConn
39
+ from unaiverse.networking.node.profile import NodeProfile
40
+ from unaiverse.streams import DataProps, BufferedDataStream
41
+ from unaiverse.utils.misc import GenException, get_key_considering_multiple_sources, save_node_addresses_to_file
42
+
43
+
44
+ class Node:
45
+
46
+ # Each node can host an agent or a world
47
+ AGENT = "agent" # Artificial agent
48
+ WORLD = "world" # World agent
49
+
50
+ # Each node outputs console text with a different color
51
+ TEXT_COLORS = ('\033[91m', '\033[94m', '\033[92m', '\033[93m')
52
+ TEXT_LAST_USED_COLOR = 0
53
+ TEXT_LOCK = threading.Lock()
54
+
55
+ def __init__(self,
56
+ hosted: Agent | World,
57
+ unaiverse_key: str | None = None,
58
+ node_name: str | None = None,
59
+ node_id: str | None = None,
60
+ hidden: bool = False,
61
+ clock_delta: float = 1. / 25.,
62
+ base_identity_dir: str = "./unaiverse_nodes_identity",
63
+ only_certified_agents: bool = False,
64
+ allowed_node_ids: list[str] | set[str] = None, # Optional: it is loaded from the online profile
65
+ world_masters_node_ids: list[str] | set[str] = None, # Optional: it is loaded from the online profile
66
+ world_masters_node_names: list[str] | set[str] = None, # Optional: it will be converted to node IDs
67
+ allow_connection_through_relay: bool = True,
68
+ talk_to_relay_based_nodes: bool = True):
69
+ """Initializes a new instance of the Node class.
70
+
71
+ Args:
72
+ hosted: The Agent or World entity hosted by this node.
73
+ unaiverse_key: The UNaIVERSE key for authentication (if None, it will be loaded from env var or cache file,
74
+ or you will be asked for it).
75
+ node_name: A human-readable name for the node (using node ID is preferable; use this or node ID, not both).
76
+ node_id: A unique identifier for the node (use this or the node name, not both).
77
+ hidden: A flag to determine if the node is hidden (i.e., only the owner of the account can see it).
78
+ clock_delta: The minimum time delta for the node's clock.
79
+ only_certified_agents: A flag to allow only certified agents to connect.
80
+ allowed_node_ids: A list or set of allowed node IDs to connect (t is loaded from the online profile).
81
+ world_masters_node_ids: A list or set of world masters' node IDs (it is also loaded from online profile).
82
+ world_masters_node_names: A list or set of world masters' node names (using IDs is preferable).
83
+ allow_connection_through_relay: A flag to allow connections through a relay.
84
+ talk_to_relay_based_nodes: A flag to allow talking to relay-based nodes.
85
+ """
86
+
87
+ # Checking main arguments
88
+ if not (isinstance(hosted, Agent) or isinstance(hosted, World)):
89
+ raise GenException("Invalid hosted entity, must be Agent or World")
90
+ if not (node_id is None or isinstance(node_id, str)):
91
+ raise GenException("Invalid node ID")
92
+ if not (node_name is None or isinstance(node_name, str)):
93
+ raise GenException("Invalid node name")
94
+ if not (node_name is None or node_id is None):
95
+ raise GenException("Cannot specify both node ID and node name")
96
+ if not (node_name is not None or node_id is not None):
97
+ raise GenException("You must specify either node ID or node name: both are missing")
98
+ if not (unaiverse_key is None or isinstance(unaiverse_key, str)):
99
+ raise GenException("Invalid UNaIVERSE key")
100
+
101
+ # Main attributes
102
+ self.node_id = node_id
103
+ self.unaiverse_key = unaiverse_key
104
+ self.hosted = hosted
105
+ self.node_type = Node.AGENT if (isinstance(hosted, Agent) and not isinstance(hosted, World)) else Node.WORLD
106
+ self.agent = hosted if self.node_type is Node.AGENT else None
107
+ self.world = hosted if self.node_type is Node.WORLD else None
108
+ self.clock = Clock(min_delta=clock_delta) # Node clock
109
+ self.conn = None # Manages the network operations in the P2P network
110
+ self.talk_to_relay_based_nodes = talk_to_relay_based_nodes
111
+
112
+ # Expected properties of the nodes that will try to connect to this one
113
+ self.only_certified_agents = only_certified_agents
114
+ self.allowed_node_ids = set(allowed_node_ids) if allowed_node_ids is not None else None
115
+ self.world_masters_node_ids = set(world_masters_node_ids) if world_masters_node_ids is not None else None
116
+
117
+ # Profile
118
+ self.profile = None
119
+ self.send_dynamic_profile_every = 10. if self.node_type is Node.WORLD else 10. # Seconds
120
+ self.get_new_token_every = 23 * 60. * 60. + 30 * 60. # Seconds (23 hours and 30 minutes, safer)
121
+
122
+ # Rendezvous
123
+ self.publish_rendezvous_every = 10.
124
+ self.last_rendezvous_time = 0.
125
+
126
+ # Automatic address update and relay refresh (if needed)
127
+ self.relay_reservation_expiry: Optional[datetime] = None
128
+ self.address_check_every = 5 * 60. # Check every 5 minutes
129
+
130
+ # Interview of newly connected nodes
131
+ self.interview_timeout = 45. # Seconds
132
+ self.connect_without_ack_timeout = 45. # Seconds
133
+
134
+ # Alive messaging
135
+ self.send_alive_every = 2.5 * 60. # Seconds
136
+ self.last_alive_time = 0.
137
+ self.skip_was_alive_check = os.getenv("NODE_IGNORE_ALIVE", "0") == "1"
138
+
139
+ # Alive messaging
140
+ self.run_start_time = 0.
141
+
142
+ # Root server-related
143
+ self.root_endpoint = 'https://unaiverse.io/api' # WARNING: EDITING THIS ADDRESS VIOLATES THE LICENSE
144
+ self.node_token = ""
145
+ self.public_key = ""
146
+
147
+ # Output console text
148
+ print_level = int(os.getenv("NODE_PRINT", "0")) # 0, 1, 2
149
+ self.print_enabled = print_level > 0
150
+ self.cursor_hidden = False
151
+ NodeSynchronizer.DEBUG = print_level > 1
152
+ NodeConn.DEBUG = print_level > 1
153
+ if print_level == 0:
154
+ self.cursor_hidden = True
155
+ with Node.TEXT_LOCK:
156
+ self.text_color = Node.TEXT_COLORS[Node.TEXT_LAST_USED_COLOR]
157
+ Node.TEXT_LAST_USED_COLOR = (Node.TEXT_LAST_USED_COLOR + 1) % len(Node.TEXT_COLORS)
158
+
159
+ # Print-related logging (for inspector only)
160
+ self._output_messages = [""] * 20
161
+ self._output_messages_ids = [-1] * 20
162
+ self._output_messages_count = 0
163
+ self._output_messages_last_pos = -1
164
+
165
+ # Attributes: handshake-related
166
+ self.agents_to_interview: dict[str, [float, NodeProfile | None]] = {} # Peer_id -> [time, profile | None]
167
+ self.agents_expected_to_send_ack = {}
168
+ self.last_rejected_agents = deque(maxlen=self.conn)
169
+ self.joining_world_info = None
170
+ self.first = True
171
+
172
+ # Inspector related
173
+ self.inspector_activated = False
174
+ self.inspector_peer_id = None
175
+ self.debug_server_running = False
176
+ self.__inspector_cache = {"behav": None, "known_streams_count": 0, "all_agents_count": 0}
177
+ self.__inspector_told_to_pause = False
178
+
179
+ # Get key
180
+ self.unaiverse_key = get_key_considering_multiple_sources(self.unaiverse_key)
181
+
182
+ # Getting node ID (retrieving by name), if it was not provided (the node is created if not existing)
183
+ if self.node_id is None:
184
+ node_ids, were_alive = self.get_node_id_by_name([node_name],
185
+ create_if_missing=True)
186
+ self.node_id = node_ids[0]
187
+ if were_alive[0]:
188
+ raise GenException(f"Cannot access node {node_name}, it is already running! "
189
+ f"(set env variable NODE_IGNORE_ALIVE=1 to ignore this control)")
190
+
191
+ # Automatically create a unique data directory for this specific node
192
+ node_identity_dir = os.path.join(base_identity_dir, self.node_id)
193
+ p2p_u_identity_dir = os.path.join(node_identity_dir, "p2p_public")
194
+ p2p_w_identity_dir = os.path.join(node_identity_dir, "p2p_private")
195
+
196
+ # Getting node ID of world masters, if needed
197
+ if world_masters_node_names is not None and len(world_masters_node_names) > 0:
198
+ master_node_ids, were_alive = self.get_node_id_by_name(world_masters_node_names,
199
+ create_if_missing=True, node_type=Node.AGENT)
200
+ for master_node_name, master_node_id in zip(world_masters_node_names, master_node_ids):
201
+ if master_node_id is None:
202
+ raise GenException(f"Cannot find world master node ID given its name: {master_node_name}")
203
+ else:
204
+ if self.world_masters_node_ids is None:
205
+ self.world_masters_node_ids = set()
206
+ self.world_masters_node_ids.add(master_node_id)
207
+
208
+ # Here you can setup max_instances, max_channels, enable_logging at libp2p level etc.
209
+ P2P.setup_library(enable_logging=os.getenv("NODE_LIBP2PLOG", "0") == "1")
210
+
211
+ offer_relay_facilities = self.node_type is Node.WORLD # Only world nodes offer relay facilities
212
+
213
+ # --- PARALLEL P2P NODE CREATION ---
214
+ # 1. Define configurations for both nodes
215
+ p2p_u_config = {
216
+ "identity_dir": p2p_u_identity_dir,
217
+ "port": int(os.getenv("NODE_STARTING_PORT", "0")),
218
+ "ips": None,
219
+ "enable_relay_client": allow_connection_through_relay,
220
+ "enable_relay_service": offer_relay_facilities,
221
+ "knows_is_public": os.getenv("NODE_IS_PUBLIC", "0") == "1",
222
+ "max_connections": 1000,
223
+ "enable_tls": os.getenv("NODE_USE_TLS", "0") == "1",
224
+ "domain_name": os.getenv("DOMAIN", None),
225
+ "tls_cert_path": os.getenv("TLS_CERT_PATH", None),
226
+ "tls_key_path": os.getenv("TLS_KEY_PATH", None),
227
+ }
228
+
229
+ p2p_w_config = {
230
+ "identity_dir": p2p_w_identity_dir,
231
+ "port": (int(os.getenv("NODE_STARTING_PORT", "0")) + 4)
232
+ if int(os.getenv("NODE_STARTING_PORT", "0")) > 0 else 0,
233
+ "ips": None,
234
+ "enable_relay_client": allow_connection_through_relay,
235
+ "enable_relay_service": offer_relay_facilities,
236
+ "knows_is_public": os.getenv("NODE_IS_PUBLIC", "0") == "1",
237
+ "max_connections": 1000,
238
+ "enable_tls": os.getenv("NODE_USE_TLS", "0") == "1",
239
+ "domain_name": os.getenv("DOMAIN", None),
240
+ "tls_cert_path": os.getenv("TLS_CERT_PATH", None),
241
+ "tls_key_path": os.getenv("TLS_KEY_PATH", None),
242
+ }
243
+
244
+ # 2. Prepare a dictionary to store results or exceptions
245
+ results = {
246
+ "p2p_u": None,
247
+ "p2p_w": None
248
+ }
249
+
250
+ # 3. Define the worker function for the threads
251
+ def create_p2p_instance(name: str, config: dict):
252
+ try:
253
+ # This is the slow, blocking call
254
+ instance = P2P(**config)
255
+ results[name] = instance
256
+ except Exception as e:
257
+ # Store the exception if creation fails
258
+ results[name] = e
259
+
260
+ # 4. Create and start both threads
261
+ thread_u = threading.Thread(target=create_p2p_instance, args=("p2p_u", p2p_u_config))
262
+ thread_w = threading.Thread(target=create_p2p_instance, args=("p2p_w", p2p_w_config))
263
+
264
+ thread_u.start()
265
+ thread_w.start()
266
+
267
+ # 5. Wait for both threads to complete
268
+ # This BLOCKS the __init__ method until both are done.
269
+ thread_u.join()
270
+ thread_w.join()
271
+
272
+ # 6. Retrieve results and check for errors
273
+ p2p_u = results["p2p_u"]
274
+ p2p_w = results["p2p_w"]
275
+
276
+ if isinstance(p2p_u, Exception):
277
+ # We must re-raise the exception to fail the Node creation
278
+ raise P2PError(f"Failed to initialize public P2P node (p2p_u): {p2p_u}") from p2p_u
279
+ if isinstance(p2p_w, Exception):
280
+ raise P2PError(f"Failed to initialize private P2P node (p2p_w): {p2p_w}") from p2p_w
281
+ if p2p_u is None or p2p_w is None:
282
+ # This should not happen if threads ran, but it's a safe check
283
+ raise P2PError("P2P node creation did not complete, but no exception was caught.")
284
+
285
+ # Get first node token
286
+ self.get_node_token(peer_ids=[p2p_u.peer_id, p2p_w.peer_id]) # Passing both the peer IDs
287
+
288
+ # Get first badge token
289
+ if self.node_type is Node.WORLD:
290
+ self.badge_token = self.__root(api="account/node/cv/badge/token/get", payload={"node_id": self.node_id})
291
+ else:
292
+ self.badge_token = None
293
+
294
+ # Get profile (static)
295
+ profile_static = self.__root(api="/account/node/profile/static/get", payload={"node_id": self.node_id})
296
+
297
+ # Getting list of allowed nodes from the static profile,
298
+ # if we did not already specify it when creating the node in the code (the code has higher priority)
299
+ if (self.allowed_node_ids is None and 'allowed_node_ids' in profile_static and
300
+ profile_static['allowed_node_ids'] is not None and len(profile_static['allowed_node_ids']) > 0):
301
+ self.allowed_node_ids = set(profile_static['allowed_node_ids'])
302
+
303
+ # Getting list of world master nodes from the static profile,
304
+ # if we did not already specify it when creating the node in the code (the code has higher priority)
305
+ if self.node_type is Node.WORLD:
306
+ if (self.world_masters_node_ids is None and 'world_masters_node_ids' in profile_static and
307
+ profile_static['world_masters_node_ids'] is not None
308
+ and len(profile_static['world_masters_node_ids']) > 0):
309
+ self.world_masters_node_ids = set(profile_static['world_masters_node_ids'])
310
+ else:
311
+ self.world_masters_node_ids = None # Clearing this in case the user specified it for a non-world node
312
+
313
+ # Creating the connection manager
314
+ # guessing max number of connections (max number of valid
315
+ # the connection manager will ensure that this limit is fulfilled)
316
+ # however, the actual number of connection attempts handled by libp2p must be higher that
317
+ self.conn = NodeConn(max_connections=profile_static['max_nr_connections'],
318
+ p2p_u=p2p_u,
319
+ p2p_w=p2p_w,
320
+ is_world_node=self.node_type is Node.WORLD,
321
+ public_key=self.public_key,
322
+ token=self.node_token)
323
+
324
+ # Get CV
325
+ cv = self.get_cv()
326
+
327
+ # Creating full node profile putting together static info, dynamic profile, adding P2P node info, CV
328
+ self.profile = NodeProfile(static=profile_static,
329
+ dynamic={'peer_id': p2p_u.peer_id,
330
+ 'peer_addresses': p2p_u.addresses,
331
+ 'private_peer_id': p2p_w.peer_id,
332
+ 'private_peer_addresses': p2p_w.addresses,
333
+ 'connections': {
334
+ 'role': self.hosted.ROLE_BITS_TO_STR[self.hosted.ROLE_PUBLIC]
335
+ },
336
+ 'world_summary': {
337
+ 'world_name':
338
+ profile_static['node_name']
339
+ if self.node_type is Node.WORLD else None
340
+ },
341
+ "world_roles_fsm": None, # This will be filled later if this is a world
342
+ "world_stats_dynamic": None, # This will be filled later if this is a world
343
+ "hidden": hidden # Marking the node as hidden (or not)
344
+ },
345
+ cv=cv) # Adding CV here
346
+
347
+ # Sharing node-level info with the hosted entity
348
+ self.hosted.set_node_info(self.clock, self.conn, self.profile, self.out, self.ask_to_get_in_touch,
349
+ self.__purge, self.agents_expected_to_send_ack, print_level)
350
+
351
+ # Finally, sending dynamic profile to the root server
352
+ # (send AFTER set_node_info, not before, since set_node_info updates the profile,
353
+ # adding world roles and state machines)
354
+ self.send_dynamic_profile()
355
+
356
+ # Save public addresses
357
+ path_to_append_addresses = os.getenv("NODE_SAVE_RUNNING_ADDRESSES")
358
+ if path_to_append_addresses is not None and os.path.exists(path_to_append_addresses):
359
+ save_node_addresses_to_file(self, public=True, dir_path=path_to_append_addresses,
360
+ filename="running.csv", append=True)
361
+
362
+ # Update lone-wolf machines to replace default wildcards (like <agent>) - the private one will be handled when
363
+ # joining a world
364
+ if self.node_type is Node.AGENT:
365
+ self.agent.behav_lone_wolf.update_wildcard("<agent>", f"{self.get_public_peer_id()}")
366
+
367
+ def out(self, msg: str):
368
+ """Prints a formatted message to the console if printing is enabled.
369
+
370
+ Args:
371
+ msg: The message to be printed.
372
+ """
373
+ if self.print_enabled:
374
+ s = (f"{self.node_type[0:2]}: " +
375
+ ((self.hosted.get_name())[0:6] + ",").ljust(7) +
376
+ f" cy: {self.clock.get_cycle()}")
377
+ s = f"[{s}] {msg}"
378
+ print(f"{self.text_color}{s}\033[0m")
379
+
380
+ if self.inspector_activated or self.debug_server_running:
381
+ last_id = self._output_messages_ids[self._output_messages_last_pos]
382
+ self._output_messages_last_pos = (self._output_messages_last_pos + 1) % len(self._output_messages)
383
+ self._output_messages_count = min(self._output_messages_count + 1, len(self._output_messages))
384
+ self._output_messages_ids[self._output_messages_last_pos] = last_id + 1
385
+ self._output_messages[self._output_messages_last_pos] = html.escape(str(msg), quote=True)
386
+
387
+ def err(self, msg: str):
388
+ """Prints a formatted error message to the console.
389
+
390
+ Args:
391
+ msg: The error message to be printed.
392
+ """
393
+ when = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
394
+ if self.print_enabled:
395
+ self.out(f"<ERROR> [{when}] " + msg)
396
+ else:
397
+ print(f"<ERROR> [{when}] " + msg)
398
+
399
+ def get_node_id_by_name(self, node_names: list[str], create_if_missing: bool = False,
400
+ node_type: str | None = None) -> tuple[list[str], list[bool]]:
401
+ """Retrieves the node ID by its name from the root server, creating a new node if it's missing and specified.
402
+
403
+ Args:
404
+ node_names: The list with the names of the nodes to retrieve.
405
+ create_if_missing: A flag to create the node if it doesn't exist (only valid for your own nodes).
406
+ node_type: The type of the node to create if missing (when create_if_missing is True) - default: the type of
407
+ the current node.
408
+
409
+ Returns:
410
+ The list of node IDs and the list of boolean flags telling if a node was already alive,
411
+ or an exception if an error occurs.
412
+ """
413
+ try:
414
+ response = self.__root("/account/node/get/id",
415
+ payload={"node_name": node_names,
416
+ "account_token": self.unaiverse_key})
417
+ node_ids = []
418
+ were_alive = []
419
+ missing = []
420
+ for i in range(0, len(response["nodes"])):
421
+ if response["nodes"][i] is not None:
422
+ node_ids.append(response["nodes"][i]["node_id"])
423
+ were_alive.append(response["nodes"][i]["was_alive"])
424
+ else:
425
+ node_ids.append(None)
426
+ were_alive.append(None)
427
+ missing.append(i)
428
+ except Exception as e:
429
+ raise GenException(f"Error while retrieving nodes named {node_names} from server! [{e}]")
430
+
431
+ if create_if_missing:
432
+ for i in missing:
433
+ node_name = node_names[i]
434
+ if "/" in node_name or "@" in node_name: # Cannot create nodes belonging to others
435
+ continue
436
+ try:
437
+ response = self.__root("/account/node/fast_register",
438
+ payload={"node_name": node_name,
439
+ "node_type": self.node_type if node_type is None else node_type,
440
+ "account_token": self.unaiverse_key})
441
+ node_ids[i] = response["node_id"]
442
+ were_alive[i] = False
443
+ except Exception as e:
444
+ raise GenException(f"Error while registering node named {node_name} in server! [{e}]")
445
+ return node_ids, were_alive
446
+
447
+ def send_alive(self) -> bool:
448
+ """Send an alive message to the root server.
449
+
450
+ Returns:
451
+ A boolean flag indicating whether the node was already live before sending this.
452
+ """
453
+ try:
454
+ response = self.__root("/account/node/alive",
455
+ payload={"node_id": self.node_id,
456
+ "account_token": self.unaiverse_key})
457
+ return response["was_alive"]
458
+ except Exception as e:
459
+ self.err(f"Error while sending alive message to server! [{e}]")
460
+
461
+ def get_node_token(self, peer_ids):
462
+ """Generates and retrieves a node token from the root server.
463
+
464
+ Args:
465
+ peer_ids: A list of public and private peer IDs.
466
+ """
467
+ response = None
468
+
469
+ for i in range(0, 3): # It will try 3 times before raising the exception...
470
+ try:
471
+ response = self.__root("/account/node/token/generate",
472
+ payload={"node_id": self.node_id,
473
+ "account_token": self.unaiverse_key
474
+ if self.node_token is None or len(self.node_token) == 0 else None,
475
+ "node_token": self.node_token, "peer_ids": json.dumps(peer_ids)})
476
+ break
477
+ except Exception as e:
478
+ if i < 2:
479
+ self.err(f"Error while getting token from server, retrying...")
480
+ time.sleep(1) # Wait a little bit
481
+ else:
482
+ raise GenException(f"Error while getting token from server [{e}]") # Raise the exception
483
+
484
+ self.node_token = response["token"]
485
+ self.public_key = response["public_key"]
486
+
487
+ # Sharing the token with the connection manager
488
+ if self.conn is not None:
489
+ self.conn.set_token(self.node_token)
490
+
491
+ def get_cv(self):
492
+ """Retrieves the node's CV (Curriculum Vitae) from the root server
493
+
494
+ Returns:
495
+ The node's CV as a dictionary.
496
+ """
497
+ for i in range(0, 3): # It will try 3 times before raising the exception...
498
+ try:
499
+ return self.__root(api="/account/node/cv/get", payload={"node_id": self.node_id})
500
+ except Exception as e:
501
+ self.err(f"Error while getting CV from server [{e}]")
502
+ if i < 2:
503
+ self.out("Retrying...")
504
+ time.sleep(1) # Wait a little bit
505
+ else:
506
+ raise GenException(f"Error while getting CV from server [{e}]")
507
+
508
+ def send_dynamic_profile(self):
509
+ """Sends the node's dynamic profile to the root server."""
510
+ try:
511
+ self.__root(api="/account/node/profile/dynamic/post", payload={"node_id": self.node_id,
512
+ "profile":
513
+ self.profile.get_dynamic_profile()})
514
+ except Exception as e:
515
+ self.err(f"Error while sending dynamic profile to from server [{e}]")
516
+
517
+ def send_badges(self):
518
+ """Sends new badges assigned by a world node to the root server and notifies the agents."""
519
+ if self.node_type is Node.WORLD:
520
+ peer_id_to_badges = self.world.get_all_badges()
521
+ if len(peer_id_to_badges) > 0:
522
+ self.out(f"Sending {len(peer_id_to_badges)} badges to root server")
523
+ for i in range(0, 3): # It will try 3 times before raising the exception...
524
+ try:
525
+ badges = [badge for _badges in peer_id_to_badges.values() for badge in _badges]
526
+ peer_ids = [peer_id for peer_id, _badges in peer_id_to_badges.items() for _ in _badges]
527
+
528
+ response = self.__root(api="/account/node/cv/badge/assign",
529
+ payload={"badges": badges,
530
+ "world_node_id": self.node_id,
531
+ "world_badge_token": self.badge_token})
532
+
533
+ # Getting the next badge token
534
+ self.badge_token = response["badge_token"]
535
+ badges_states = response["badges_states"] # List of booleans
536
+
537
+ # Check if posting went well and saving the set of peer IDs to contact
538
+ peer_ids_to_notify = set()
539
+ for z in range(0, len(badges_states)):
540
+ ret = badges_states[z]
541
+ if 'state' not in ret or 'code' not in ret['state'] or 'message' not in ret['state']:
542
+ self.err(f"Error while posting a badge assigned to {peer_ids[z]}. Badge: {badges[z]}. "
543
+ f"Error message: invalid response format")
544
+ else:
545
+ if ret['state']['code'] != "ok":
546
+ self.err(f"Error while posting a badge assigned to {peer_ids[z]}. "
547
+ f"Badge: {badges[z]}. "
548
+ f"Error message: {ret['state']['message']}")
549
+ else:
550
+ peer_ids_to_notify.add(peer_ids[z])
551
+
552
+ # Notify agents
553
+ for peer_id in peer_ids_to_notify:
554
+ if not self.conn.send(peer_id, channel_trail=None, content=None,
555
+ content_type=Msg.GET_CV_FROM_ROOT):
556
+ self.err(f"Error while sending the request to re-download CV to peer {peer_id}")
557
+
558
+ # Clearing
559
+ self.world.clear_badges()
560
+ break
561
+ except Exception as e:
562
+ self.err(f"Error while sending badges to server or when notifying peers [{e}]")
563
+ if i < 2:
564
+ self.out("Retrying...")
565
+ time.sleep(1) # Wait a little bit
566
+ else:
567
+ self.err(f"Couldn't complete badge sending or notification procedure (stop trying)")
568
+
569
+ def get_public_addresses(self) -> list[str]:
570
+ """Returns the public addresses of the P2P node
571
+
572
+ Returns:
573
+ The list of public addresses.
574
+ """
575
+ return self.conn[NodeConn.P2P_PUBLIC].addresses
576
+
577
+ def get_world_addresses(self) -> list[str]:
578
+ """Returns the world addresses of the P2P node
579
+
580
+ Returns:
581
+ The list of world addresses.
582
+ """
583
+ return self.conn[NodeConn.P2P_WORLD].addresses
584
+
585
+ def get_public_peer_id(self) -> str:
586
+ """Returns the public peer ID of the P2P node
587
+
588
+ Returns:
589
+ The public peer ID.
590
+ """
591
+ return self.conn[NodeConn.P2P_PUBLIC].peer_id
592
+
593
+ def get_world_peer_id(self) -> str:
594
+ """Returns the world peer ID of the P2P node
595
+
596
+ Returns:
597
+ The world peer ID.
598
+ """
599
+ return self.conn[NodeConn.P2P_WORLD].peer_id
600
+
601
+ def ask_to_get_in_touch(self, node_name: str | None = None, addresses: list[str] | None = None, public: bool = True,
602
+ before_updating_pools_fcn=None, run_count: int = 0):
603
+ """Tries to connect to another agent or world node.
604
+
605
+ Args:
606
+ node_name: Name of the node to join (alternative to addresses below)
607
+ addresses: A list of network addresses to connect to (alternative to node_name).
608
+ public: A boolean flag indicating whether to use the public or world P2P network.
609
+ before_updating_pools_fcn: A function to call before updating the connection pools.
610
+ run_count: The number of connection attempts made.
611
+
612
+ Returns:
613
+ The peer ID of the connected node if successful, otherwise None.
614
+ """
615
+
616
+ # Checking arguments
617
+ if (node_name is None and addresses is None) or (node_name is not None and addresses is not None):
618
+ raise GenException("Cannot specify both node_name and addresses or none of them, check your code!")
619
+
620
+ # Getting addresses, if needed
621
+ if addresses is None:
622
+ addresses = self.__root(api="account/node/get/addresses",
623
+ payload={"node_name": node_name, "account_token": self.unaiverse_key})["addresses"]
624
+
625
+ # Connecting
626
+ self.out("Connecting to another agent/world...")
627
+ peer_id, through_relay = self.conn.connect(addresses,
628
+ p2p_name=NodeConn.P2P_PUBLIC if public else NodeConn.P2P_WORLD)
629
+
630
+ if through_relay:
631
+ print("Warning: this connection goes through a relay-based circuit, "
632
+ "so a third-party node is involved in the communication")
633
+
634
+ if peer_id is not None and (not through_relay or self.talk_to_relay_based_nodes):
635
+
636
+ # Ping to test the readiness of the established connection
637
+ self.out(f"Connected, ping-pong...")
638
+ if not self.conn.send(peer_id, channel_trail=None, content_type=Msg.MISC, content={"ping": "pong"},
639
+ p2p=self.conn.p2p_name_to_p2p[NodeConn.P2P_PUBLIC if public else NodeConn.P2P_WORLD]):
640
+ if run_count < 2:
641
+ return self.ask_to_get_in_touch(addresses=addresses, public=public,
642
+ before_updating_pools_fcn=before_updating_pools_fcn,
643
+ run_count=run_count+1)
644
+ else:
645
+ self.err("Connection failed! (ping-pong max trials exceeded)")
646
+ return None
647
+
648
+ self.out("Connected, updating pools...")
649
+ if before_updating_pools_fcn is not None:
650
+ before_updating_pools_fcn(peer_id)
651
+ self.conn.update()
652
+
653
+ self.agents_expected_to_send_ack[peer_id] = self.clock.get_time()
654
+ self.out(f"Current set of {len(self.agents_expected_to_send_ack)} connected peer IDs that will get our "
655
+ f"profile and are expected to send a confirmation: "
656
+ f"{self.agents_expected_to_send_ack.keys()}")
657
+ return peer_id
658
+ else:
659
+ self.err("Connection failed!")
660
+ return None
661
+
662
+ def ask_to_join_world(self, node_name: str | None = None, addresses: list[str] | None = None, **kwargs):
663
+ """Initiates a request to join a world.
664
+
665
+ Args:
666
+ node_name: The name of the node hosting the world to join (alternative to addresses below).
667
+ addresses: A list of network addresses of the world node (alternative to world_name).
668
+ **kwargs: Additional options for joining the world.
669
+
670
+ Returns:
671
+ The public peer ID of the world node if the connection request is successful, otherwise None.
672
+ """
673
+ print("Asking to join world...")
674
+
675
+ # Leave an already entered world (if any)
676
+ world_peer_id = self.profile.get_dynamic_profile()['connections']['world_peer_id']
677
+ if world_peer_id is not None:
678
+ self.leave(world_peer_id)
679
+
680
+ # Connecting to the world (public)
681
+ peer_id = self.ask_to_get_in_touch(node_name=node_name, addresses=addresses, public=True)
682
+
683
+ # Saving info
684
+ if peer_id is not None:
685
+ print("Connected on the public network, waiting for handshake...")
686
+ self.joining_world_info = {"world_public_peer_id": peer_id, "options": kwargs}
687
+ else:
688
+ print("Failed to join world!")
689
+ return peer_id
690
+
691
+ def leave(self, peer_id: str):
692
+ """Disconnects the node from a specific peer, typically a world.
693
+
694
+ Args:
695
+ peer_id: The peer ID of the node to leave.
696
+ """
697
+
698
+ if not isinstance(peer_id, str):
699
+ self.err(f"Invalid argument provided to leave(...): {peer_id}")
700
+ return
701
+
702
+ print(f"Leaving {peer_id}...")
703
+
704
+ dynamic_profile = self.profile.get_dynamic_profile()
705
+
706
+ if peer_id == dynamic_profile['connections']['world_peer_id']:
707
+ print("Leaving world...")
708
+
709
+ # Clearing world-related lists in the connection manager (to avoid world agent to connect again)
710
+ self.conn.set_world(None)
711
+ self.conn.set_world_agents_list(None)
712
+ self.conn.set_world_masters_list(None)
713
+
714
+ # Disconnecting all connected world-related agents, including world node (it clears roles too)
715
+ self.conn.remove_all_world_agents()
716
+
717
+ # Better clear this as well
718
+ if peer_id in self.agents_expected_to_send_ack:
719
+ del self.agents_expected_to_send_ack[peer_id]
720
+
721
+ # Clear profile
722
+ dynamic_profile['connections']['world_peer_id'] = None
723
+ dynamic_profile['connections']['world_agents'] = None
724
+ dynamic_profile['connections']['world_masters'] = None
725
+ self.profile.mark_change_in_connections()
726
+
727
+ # Clearing agent-level info
728
+ self.agent.clear_world_related_data()
729
+
730
+ # Clearing all joining options
731
+ self.joining_world_info = None
732
+ else:
733
+ if peer_id in self.hosted.all_agents:
734
+ self.hosted.remove_agent(peer_id)
735
+ self.conn.remove(peer_id)
736
+
737
+ def leave_world(self):
738
+ """Initiates the process of leaving a world.
739
+
740
+ Returns:
741
+ None.
742
+ """
743
+ if self.profile.get_dynamic_profile()['connections']['world_peer_id'] is not None:
744
+ self.agent.accept_new_role(self.agent.ROLE_PUBLIC)
745
+ self.agent.world_profile = None
746
+ self.leave(self.profile.get_dynamic_profile()['connections']['world_peer_id'])
747
+
748
+ def run(self, cycles: int | None = None, max_time: float | None = None, interact_mode_opts: dict | None = None):
749
+ """Starts the main execution loop for the node.
750
+
751
+ Args:
752
+ cycles: The number of clock cycles to run the loop for. If None, runs indefinitely.
753
+ max_time: The maximum time in seconds to run the loop. If None, runs indefinitely.
754
+ interact_mode_opts: A dictionary of options to enable interactive mode.
755
+ """
756
+ try:
757
+ if self.cursor_hidden:
758
+ sys.stdout.write("\033[?25l") # Hide cursor
759
+
760
+ last_dynamic_profile_time = self.clock.get_time()
761
+ last_get_token_time = self.clock.get_time()
762
+ last_address_check_time = self.clock.get_time()
763
+ if not (cycles is None or cycles > 0):
764
+ raise GenException("Invalid number of cycles")
765
+
766
+ # Interactive mode (useful when chatting with lone wolves)
767
+ keyboard_queue = None
768
+ keyboard_listener = None
769
+ processor_net_hash = None
770
+ processor_img_stream = None
771
+ processor_text_stream = None
772
+ cap = None
773
+ ready_to_interact = False
774
+
775
+ if interact_mode_opts is not None:
776
+ if self.agent is None:
777
+ raise GenException("Interactive mode is only valid for agents")
778
+
779
+ processor_text_net_hash = None
780
+ processor_img_net_hash = None
781
+ looking_for_public_streams = "lone_wolf_peer_id" in interact_mode_opts
782
+ for net_hash, stream_dict in self.agent.proc_streams.items():
783
+ for stream in stream_dict.values():
784
+ if (processor_text_stream is None and stream.props.is_public() == looking_for_public_streams
785
+ and stream.props.is_text()):
786
+ processor_text_stream = stream
787
+ processor_text_net_hash = net_hash
788
+ if (processor_img_stream is None and stream.props.is_public() == looking_for_public_streams
789
+ and stream.props.is_img()):
790
+ processor_img_stream = stream
791
+ processor_img_net_hash = net_hash
792
+
793
+ if processor_text_net_hash is None:
794
+ raise GenException("Interactive mode requires a processor that generates a text stream")
795
+ if not (processor_img_net_hash is None or (processor_text_net_hash == processor_img_net_hash)):
796
+ raise GenException("Interactive mode requires the same processor to generate text and img streams")
797
+ processor_net_hash = processor_text_net_hash
798
+
799
+ def keyboard_listener(k_queue):
800
+ while True:
801
+ webcam_shot = None
802
+ keyboard_msg = input() # Get from keyboards
803
+ if cap is not None:
804
+ ret, got_shot = cap.read() # Get from webcam
805
+ if ret:
806
+ target_area = 224 * 224
807
+ webcam_shot = Image.fromarray(cv2.cvtColor(got_shot, cv2.COLOR_BGR2RGB))
808
+ width, height = webcam_shot.size
809
+ current_area = width * height
810
+
811
+ if current_area > target_area:
812
+ scale_factor = math.sqrt(target_area / current_area)
813
+ new_width = int(round(width * scale_factor))
814
+ new_height = int(round(height * scale_factor))
815
+ webcam_shot = webcam_shot.resize((new_width, new_height),
816
+ Image.Resampling.LANCZOS)
817
+
818
+ if keyboard_msg is not None and len(keyboard_msg) > 0:
819
+ k_queue.put((keyboard_msg, webcam_shot)) # Store in the asynch queue
820
+
821
+ if keyboard_msg.strip() == "exit" or keyboard_msg.strip() == "quit":
822
+ break
823
+
824
+ if not self.agent.in_world(): # If the world disconnected
825
+ break
826
+
827
+ keyboard_queue = queue.Queue() # Create a thread-safe queue for communication
828
+ keyboard_listener = threading.Thread(target=keyboard_listener, args=(keyboard_queue,), daemon=True)
829
+
830
+ if self.clock.get_cycle() == -1:
831
+ print("Running " + ("agent node" if self.agent else "world node") + " " +
832
+ f"(public: {self.get_public_peer_id()}, private: {self.get_world_peer_id()})...")
833
+
834
+ # Main loop
835
+ must_quit = False
836
+ self.run_start_time = self.clock.get_time()
837
+ while not must_quit:
838
+
839
+ # Sending alive message every "K" seconds
840
+ if self.clock.get_time() - self.last_alive_time >= self.send_alive_every:
841
+ was_alive = self.send_alive()
842
+
843
+ # Checking only at the first run
844
+ if self.last_alive_time == 0 and was_alive and not self.skip_was_alive_check:
845
+ print(f"The node is already alive, maybe running in a different machine? "
846
+ f"(set env variable NODE_IGNORE_ALIVE=1 to ignore this control)")
847
+ break # Stopping the running cycle
848
+ self.last_alive_time = self.clock.get_time()
849
+
850
+ # Check inspector
851
+ if self.inspector_activated:
852
+ if self.__inspector_told_to_pause:
853
+ print("Paused by the inspector, waiting...")
854
+
855
+ while self.__inspector_told_to_pause:
856
+ if not self.inspector_activated: # Disconnected
857
+ self.__inspector_told_to_pause = False
858
+ print("Inspector is not active/connected anymore, resuming...")
859
+ break
860
+
861
+ public_messages = self.conn.get_messages(p2p_name=NodeConn.P2P_PUBLIC)
862
+ for msg in public_messages:
863
+ if msg.content_type == Msg.INSPECT_CMD:
864
+
865
+ # Unpacking piggyback
866
+ sender_node_id, sender_inspector_mode_on = (msg.piggyback[0:-1],
867
+ msg.piggyback[-1] == "1")
868
+
869
+ # Is message from inspector?
870
+ sender_is_inspector = (sender_node_id == self.profile.get_static_profile()[
871
+ 'inspector_node_id'] and
872
+ sender_inspector_mode_on)
873
+
874
+ if sender_is_inspector:
875
+ self.__handle_inspector_command(msg.content['cmd'], msg.content['arg'])
876
+ else:
877
+ self.err("Inspector command was not sent by the expected inspector node ID "
878
+ "or no inspector connected")
879
+ self.__purge(msg.sender)
880
+ time.sleep(0.1)
881
+
882
+ # Move to the next cycle
883
+ while not self.clock.next_cycle():
884
+ time.sleep(0.001) # Seconds (lowest possible granularity level)
885
+
886
+ self.out(f">>> Starting clock cycle {self.clock.get_cycle()} <<<")
887
+
888
+ # Handle new connections or lost connections
889
+ self.__handle_network_connections()
890
+
891
+ # Handle (read, execute) received network data/commands
892
+ self.__handle_network_messages(interact_mode_opts=interact_mode_opts)
893
+
894
+ # Stream live data (generated and environmental)
895
+ if len(self.hosted.all_agents) > 0:
896
+ if self.node_type is Node.WORLD:
897
+ if self.first is True:
898
+ self.first = False
899
+ for net_hash, stream_dict in self.hosted.known_streams.items():
900
+ for stream_obj in stream_dict.values():
901
+ if isinstance(stream_obj, BufferedDataStream):
902
+ stream_obj.restart()
903
+ self.hosted.send_stream_samples()
904
+
905
+ # Trigger HSM of the agent
906
+ if self.node_type is Node.AGENT:
907
+ if interact_mode_opts is not None:
908
+ try:
909
+
910
+ # Waiting until we meet a state named "ready"
911
+ if not ready_to_interact:
912
+ behav = self.agent.behav_lone_wolf \
913
+ if "lone_wolf_peer_id" in interact_mode_opts else self.agent.behav
914
+ if behav.state == "ready":
915
+ ready_to_interact = True
916
+ keyboard_listener.start()
917
+ cap = cv2.VideoCapture(0) if processor_img_stream is not None else None
918
+ print(f"\n*** Entering interactive text mode ***\n\n👉 ", end="")
919
+
920
+ original_stdout = sys.stdout # Valid screen-related stream
921
+ sys.stdout = open('interact_stdout.txt',
922
+ 'w') # Open(os.devnull, 'w') # null stream
923
+ interact_mode_opts["stdout"] = [original_stdout, sys.stdout]
924
+
925
+ # Getting message from keyboard
926
+ msg, image_pil = keyboard_queue.get_nowait()
927
+
928
+ # Quit?
929
+ msg = msg.strip()
930
+ if msg == "exit" or msg == "quit":
931
+ must_quit = True
932
+ interact_mode_opts["stdout"][1].close()
933
+ if cap is not None:
934
+ cap.release()
935
+ else:
936
+
937
+ # Asking the to generate (the request will be immediately sent)
938
+ if "lone_wolf_peer_id" in interact_mode_opts:
939
+ behav = self.agent.behav_lone_wolf
940
+ other_behav = self.agent.behav
941
+
942
+ other_behav.enable(False)
943
+ behav.enable(True)
944
+ self.agent.ask_gen(agent=interact_mode_opts["lone_wolf_peer_id"],
945
+ u_hashes=[processor_net_hash],
946
+ samples=1)
947
+ behav.enable(False)
948
+ else:
949
+ self.agent.behav.request_action(action_name="ask_gen",
950
+ args={},
951
+ signature=self.get_world_peer_id(),
952
+ timestamp=self.clock.get_time(),
953
+ uuid=None)
954
+ behav = self.agent.behav
955
+ other_behav = self.agent.behav_lone_wolf
956
+ self.agent.behave()
957
+
958
+ # Loading the message and image to the processor's output streams
959
+ # they will be sent at the next clock cycle
960
+ other_behav.enable(False)
961
+ behav.enable(True)
962
+ if processor_img_stream is not None:
963
+ [msg, image_pil], _ = self.agent.generate(input_net_hashes=None,
964
+ inputs=[msg, image_pil])
965
+ processor_text_stream.set(msg)
966
+ processor_img_stream.set(image_pil)
967
+ else:
968
+ [msg], _ = self.agent.generate(input_net_hashes=None,
969
+ inputs=[msg])
970
+ processor_text_stream.set(msg)
971
+ behav.enable(False)
972
+ except queue.Empty:
973
+ self.agent.behave() # If nothing has been typed (+ enter)
974
+ else:
975
+
976
+ # Ordinary behaviour
977
+ self.agent.behave()
978
+
979
+ # Send dynamic profile every "N" seconds
980
+ if (self.clock.get_time() - last_dynamic_profile_time >= self.send_dynamic_profile_every
981
+ and self.profile.connections_changed()):
982
+ try:
983
+ last_dynamic_profile_time = self.clock.get_time()
984
+ self.profile.unmark_change_in_connections()
985
+ self.send_badges() # Sending and clearing badges
986
+ self.send_dynamic_profile() # Sending
987
+ except Exception as e:
988
+ self.err(f"Error while sending the update dynamic profile (or badges) to the server "
989
+ f"(trying to go ahead...) [{e}]")
990
+
991
+ # Getting a new token every "N" seconds
992
+ if self.clock.get_time() - last_get_token_time >= self.get_new_token_every:
993
+ self.get_node_token(peer_ids=[self.get_public_peer_id(), self.get_world_peer_id()])
994
+ last_get_token_time = self.clock.get_time()
995
+
996
+ # Check for address changes every "N" seconds
997
+ if self.clock.get_time() - last_address_check_time >= self.address_check_every:
998
+ try:
999
+ self.out("Performing periodic check for address changes...")
1000
+ last_address_check_time = self.clock.get_time()
1001
+ current_public_addrs = self.conn.p2p_public.get_node_addresses()
1002
+ current_private_addrs = self.conn.p2p_world.get_node_addresses()
1003
+ profile_public_addrs = self.profile.get_dynamic_profile().get('peer_addresses', [])
1004
+ profile_private_addrs = self.profile.get_dynamic_profile().get('private_peer_addresses', [])
1005
+
1006
+ # TODO: if public addresses changed... (if this makes any sense)
1007
+ if set(current_public_addrs) != set(profile_public_addrs):
1008
+ self.out(f"Address change detected for the public instance! "
1009
+ f"New addresses: {current_public_addrs}")
1010
+
1011
+ # Update profile in-place
1012
+ # address_list = self.profile.get_dynamic_profile()['peer_addresses']
1013
+ # address_list.clear()
1014
+ # address_list.extend(current_public_addrs)
1015
+ # self.profile.mark_change_in_connections()
1016
+
1017
+ # If private addresses changed, update the profile and notify the world
1018
+ elif set(current_private_addrs) != set(profile_private_addrs):
1019
+ self.out(f"Address change detected for the private instance! "
1020
+ f"New addresses: {current_public_addrs}")
1021
+
1022
+ # Update profile in-place
1023
+ address_list = self.profile.get_dynamic_profile()['private_peer_addresses']
1024
+ address_list.clear()
1025
+ address_list.extend(current_private_addrs)
1026
+ # self.profile.mark_change_in_connections()
1027
+
1028
+ world_peer_id = (
1029
+ self.profile.get_dynamic_profile().get('connections', {}).get('world_peer_id'))
1030
+ if self.node_type is Node.AGENT and world_peer_id:
1031
+ self.out("Notifying world of address change...")
1032
+ self.conn.send(
1033
+ world_peer_id, content_type=Msg.ADDRESS_UPDATE, channel_trail=None,
1034
+ content={'addresses': self.profile.get_dynamic_profile()['private_peer_addresses']}
1035
+ )
1036
+ else:
1037
+ self.out("No address changes detected.")
1038
+ except Exception as e:
1039
+ self.err(f"Failed to check for address updates: {e}")
1040
+
1041
+ # Refresh relay reservation if nearing expiration
1042
+ if self.relay_reservation_expiry is not None:
1043
+ time_to_expiry = self.relay_reservation_expiry - datetime.now(timezone.utc)
1044
+ if time_to_expiry < timedelta(minutes=15):
1045
+ self.out("Relay reservation nearing expiration. Attempting to renew...")
1046
+ try:
1047
+ world_private_peer_id = self.profile.get_dynamic_profile()['connections']['world_peer_id']
1048
+ new_expiry_utc = self.conn.p2p_world.reserve_on_relay(world_private_peer_id)
1049
+ self.relay_reservation_expiry = datetime.fromisoformat(
1050
+ new_expiry_utc.replace('Z', '+00:00'))
1051
+ self.out(f"Relay reservation renewed. New expiration: "
1052
+ f"{self.relay_reservation_expiry.strftime('%Y-%m-%d %H:%M:%S')} UTC")
1053
+ except Exception as e:
1054
+ self.err(f"Failed to renew relay reservation: {e}. Node may become unreachable.")
1055
+ self.relay_reservation_expiry = None # Stop trying if it fails
1056
+
1057
+ # Taking to the inspector
1058
+ if self.inspector_activated:
1059
+ self.__send_to_inspector()
1060
+
1061
+ # Stop conditions
1062
+ if cycles is not None and ((self.clock.get_cycle() + 1) >= cycles):
1063
+ break
1064
+ if max_time is not None and (self.clock.get_time() - self.run_start_time) >= max_time:
1065
+ break
1066
+
1067
+ except KeyboardInterrupt:
1068
+ if self.cursor_hidden:
1069
+ sys.stdout.write("\033[?25h") # Re-enabling cursor
1070
+ if cycles == 1:
1071
+ raise KeyboardInterrupt # Node synch will catch this
1072
+ else:
1073
+ print("\nDetected Ctrl+C! Exiting gracefully...")
1074
+
1075
+ except Exception as e:
1076
+ if self.cursor_hidden:
1077
+ sys.stdout.write("\033[?25h") # Re-enabling cursor
1078
+ print(f"An error occurred: {e}")
1079
+ traceback.print_exc()
1080
+
1081
+ def __handle_network_connections(self):
1082
+ """Manages new and lost network connections."""
1083
+
1084
+ # Getting fresh lists of existing world agents and world masters (from the rendezvous)
1085
+ if self.node_type is Node.AGENT:
1086
+ self.out("Updating list of world agents and world masters by using data from the rendezvous")
1087
+ self.conn.set_world_agents_and_world_masters_lists_from_rendezvous()
1088
+
1089
+ # Updating connection pools, getting back the lists (well, dictionaries) of new agents and lost agents
1090
+ new_peer_ids_by_pool, removed_peer_ids_by_pool = self.conn.update()
1091
+ if len(new_peer_ids_by_pool) > 0 or len(removed_peer_ids_by_pool) > 0:
1092
+ self.out("Current status of the pools, right after the update:\n" + str(self.conn))
1093
+
1094
+ # Checking if some peers were removed
1095
+ an_agent_left_the_world = False
1096
+ removed_peers = False
1097
+ for pool_name, removed_peer_ids in removed_peer_ids_by_pool.items():
1098
+ for peer_id in removed_peer_ids:
1099
+ removed_peers = True
1100
+ self.out("Removing a not-connected-anymore peer, "
1101
+ "pool_name: " + pool_name + ", peer_id: " + peer_id + "...")
1102
+ self.__purge(peer_id)
1103
+
1104
+ # Checking if we removed an agent from this world
1105
+ if self.node_type is Node.WORLD and pool_name in self.conn.WORLD:
1106
+ an_agent_left_the_world = True
1107
+
1108
+ # Check if the world disconnected: in that case, disconnect all the other agents in the world and leave
1109
+ if self.node_type is Node.AGENT and pool_name in self.conn.WORLD_NODE:
1110
+ self.leave_world()
1111
+
1112
+ # Checking if the inspector disconnected
1113
+ if peer_id == self.inspector_peer_id:
1114
+ self.inspector_activated = False
1115
+ self.inspector_peer_id = None
1116
+ self.__inspector_cache = {"behav": None, "known_streams_count": 0, "all_agents_count": 0}
1117
+ print("Inspector disconnected")
1118
+
1119
+ # Handling newly connected peers
1120
+ an_agent_joined_the_world = False
1121
+ added_peers = False
1122
+ for pool_name, new_peer_ids in new_peer_ids_by_pool.items():
1123
+ for peer_id in new_peer_ids:
1124
+ added_peers = True
1125
+ self.out("Processing a newly connected peers, "
1126
+ "pool_name: " + pool_name + ", peer_id: " + peer_id + "...")
1127
+
1128
+ # If this is a world node, it is time to tell the world object that a new agent is there
1129
+ if self.node_type is Node.WORLD and pool_name in self.conn.WORLD:
1130
+ self.out("Not considering interviewing since this is a world and the considered peer is in the"
1131
+ " world pools")
1132
+
1133
+ if peer_id in self.agents_to_interview:
1134
+
1135
+ # Getting the new agent profile
1136
+ profile = self.agents_to_interview[peer_id][1] # [time, profile]
1137
+
1138
+ # Adding the new agent to the world object
1139
+ if not self.world.add_agent(peer_id=peer_id, profile=profile):
1140
+ self.__purge(peer_id)
1141
+ continue
1142
+
1143
+ # Clearing the profile from the interviews
1144
+ del self.agents_to_interview[peer_id] # Removing from the queue (private peer id)
1145
+ an_agent_joined_the_world = True
1146
+
1147
+ # Replacing multi-address with what comes from the profile (there are more addresses there!)
1148
+ self.conn.set_addresses_in_peer_info(peer_id,
1149
+ profile.get_dynamic_profile()['private_peer_addresses'])
1150
+ else:
1151
+
1152
+ # This agent tried to connect to a world "directly", without passing through the
1153
+ # public handshake
1154
+ self.__purge(peer_id)
1155
+ continue
1156
+
1157
+ continue # Nothing else to do
1158
+
1159
+ # Both if this is an agent or a world, checks if the newly connected agent can be added or not to the
1160
+ # queue of agents to interview
1161
+ if pool_name not in self.conn.OUTGOING:
1162
+
1163
+ # Trying to add to the queue
1164
+ enqueued_for_interview = self.__interview_enqueue(peer_id)
1165
+
1166
+ # If the agent is rejected at this stage, we disconnect from its peer
1167
+ if not enqueued_for_interview:
1168
+ self.out(f"Not enqueued for interview, removing peer (disconnecting {peer_id})")
1169
+ self.__purge(peer_id)
1170
+ else:
1171
+ self.out("Enqueued for interview")
1172
+
1173
+ # Updating list of world agents & friends, if needed
1174
+ # (it happens only if the node hosts a world, otherwise 'an_agent_joined_the_world' and
1175
+ # 'an_agent_left_the_world' are certainly False)
1176
+ world_agents_peer_infos = None
1177
+ world_masters_peer_infos = None
1178
+ if self.node_type is Node.WORLD:
1179
+ enter_left = an_agent_joined_the_world or an_agent_left_the_world
1180
+ timeout = (self.clock.get_time() - self.last_rendezvous_time) >= self.publish_rendezvous_every
1181
+
1182
+ if enter_left or timeout or self.world.role_changed_by_world or self.world.received_address_update:
1183
+ if enter_left or self.world.role_changed_by_world:
1184
+
1185
+ # Updating world-node profile with the summary of currently connected agents in the world
1186
+ world_agents_peer_infos = self.conn.get_all_connected_peer_infos(NodeConn.WORLD_AGENTS)
1187
+ world_masters_peer_infos = self.conn.get_all_connected_peer_infos(NodeConn.WORLD_MASTERS)
1188
+
1189
+ dynamic_profile = self.profile.get_dynamic_profile()
1190
+ dynamic_profile['world_summary']['world_agents'] = world_agents_peer_infos
1191
+ dynamic_profile['world_summary']['world_masters'] = world_masters_peer_infos
1192
+ dynamic_profile['world_summary']["world_agents_count"] = len(world_agents_peer_infos)
1193
+ dynamic_profile['world_summary']["world_masters_count"] = len(world_masters_peer_infos)
1194
+ dynamic_profile['world_summary']["total_agents"] = (len(world_agents_peer_infos) +
1195
+ len(world_masters_peer_infos))
1196
+ self.profile.mark_change_in_connections()
1197
+
1198
+ # Publish updated list of (all) world agents (i.e., both agents and masters)
1199
+ world_all_peer_infos = self.conn.get_all_connected_peer_infos(NodeConn.WORLD)
1200
+ if not self.conn.publish(self.conn.p2p_world.peer_id, f"{self.conn.p2p_world.peer_id}::ps:rv",
1201
+ content_type=Msg.WORLD_AGENTS_LIST,
1202
+ content={"peers": world_all_peer_infos,
1203
+ "update_count": self.clock.get_cycle()}):
1204
+ self.err("Failed to publish the updated list of (all) world agents (ignoring)")
1205
+ else:
1206
+ self.last_rendezvous_time = self.clock.get_time()
1207
+ self.out(f"Rendezvous messages just published "
1208
+ f"(tag: {self.clock.get_cycle()}, peers: {len(world_all_peer_infos)})")
1209
+
1210
+ # Clearing
1211
+ self.world.role_changed_by_world = False
1212
+ self.world.received_address_update = False
1213
+
1214
+ # Updating list of node connections (being this a world or a plain agent)
1215
+ if added_peers or removed_peers:
1216
+
1217
+ # The following could have been already computed in the code above, let's reuse
1218
+ if world_agents_peer_infos is None:
1219
+ world_agents_peer_infos = self.conn.get_all_connected_peer_infos(NodeConn.WORLD_AGENTS)
1220
+ if world_masters_peer_infos is None:
1221
+ world_masters_peer_infos = self.conn.get_all_connected_peer_infos(NodeConn.WORLD_MASTERS)
1222
+ world_private_peer_id = self.conn.get_all_connected_peer_infos(NodeConn.WORLD_NODE)
1223
+ world_private_peer_id = world_private_peer_id[0]['id'] if len(world_private_peer_id) > 0 else None
1224
+
1225
+ # This is only computed here
1226
+ public_agents_peer_infos = self.conn.get_all_connected_peer_infos(NodeConn.PUBLIC)
1227
+
1228
+ # Updating node profile with the summary of currently connected peers
1229
+ dynamic_profile = self.profile.get_dynamic_profile()
1230
+ dynamic_profile['connections']['public_agents'] = public_agents_peer_infos
1231
+ dynamic_profile['connections']['world_agents'] = world_agents_peer_infos
1232
+ dynamic_profile['connections']['world_masters'] = world_masters_peer_infos
1233
+ dynamic_profile['connections']['world_peer_id'] = world_private_peer_id
1234
+ self.profile.mark_change_in_connections()
1235
+
1236
+ def __handle_network_messages(self, interact_mode_opts=None):
1237
+ """Handles and processes all incoming network messages.
1238
+
1239
+ Args:
1240
+ interact_mode_opts: A dictionary of options for interactive mode.
1241
+ """
1242
+ # Fetching all messages,
1243
+ public_messages = self.conn.get_messages(p2p_name=NodeConn.P2P_PUBLIC)
1244
+ world_messages = self.conn.get_messages(p2p_name=NodeConn.P2P_WORLD)
1245
+
1246
+ self.out("Got " + str(len(public_messages)) + " messages from the public net")
1247
+ self.out("Got " + str(len(world_messages)) + " messages from the world/private net")
1248
+
1249
+ # Process all messages
1250
+ all_messages = public_messages + world_messages
1251
+ if len(all_messages) > 0:
1252
+ self.out("Processing all messages...")
1253
+
1254
+ for i, msg in enumerate(all_messages):
1255
+ if i < len(public_messages):
1256
+ self.out("Processing public message " + str(i + 1) + "/"
1257
+ + str(len(public_messages)) + ": " + str(msg))
1258
+ else:
1259
+ self.out("Processing world/private message " + str(i - len(public_messages) + 1)
1260
+ + "/" + str(len(world_messages)) + ": " + str(msg))
1261
+
1262
+ # Checking
1263
+ if not isinstance(msg, Msg):
1264
+ self.err("Expected message of type Msg, got {} (skipping)".format(type(msg)))
1265
+ continue
1266
+
1267
+ # Unpacking piggyback
1268
+ sender_node_id, sender_inspector_mode_on = (msg.piggyback[0:-1],
1269
+ msg.piggyback[-1] == "1")
1270
+
1271
+ # Is message from inspector?
1272
+ sender_is_inspector = (sender_node_id == self.profile.get_static_profile()['inspector_node_id'] and
1273
+ sender_inspector_mode_on)
1274
+
1275
+ # (A) received a profile
1276
+ if msg.content_type == Msg.PROFILE:
1277
+ self.out("Received a profile...")
1278
+
1279
+ # Checking the received profile
1280
+ # (recall that a profile sent through the world connection to the world node will be considered
1281
+ # not acceptable)
1282
+ profile = NodeProfile.from_dict(msg.content)
1283
+ is_an_already_known_agent = msg.sender in self.hosted.all_agents
1284
+
1285
+ if is_an_already_known_agent:
1286
+ self.out("Editing information of an already added agent " + msg.sender)
1287
+
1288
+ if not self.hosted.add_agent(peer_id=msg.sender, profile=profile):
1289
+ self.__purge(msg.sender)
1290
+ else:
1291
+ is_expected_and_acceptable_profile = self.__interview_check_profile(peer_id=msg.sender,
1292
+ node_id=sender_node_id,
1293
+ profile=profile)
1294
+
1295
+ if not is_expected_and_acceptable_profile:
1296
+ self.err("Unexpected or unacceptable profile, removing (disconnecting) " + msg.sender)
1297
+ self.__purge(msg.sender)
1298
+ else:
1299
+
1300
+ # If the node hosts a world and gets an expected and acceptable profile from the public network,
1301
+ # assigns a role and sends the world profile (which includes private peer ID) and role to the
1302
+ # requester
1303
+ if (self.node_type is Node.WORLD and self.conn.is_public(peer_id=msg.sender) and
1304
+ not sender_is_inspector):
1305
+ self.out("Sending world approval message, profile, and assigned role to " + msg.sender +
1306
+ " (and switching peer ID in the interview queue)...")
1307
+ is_world_master = (self.world_masters_node_ids is not None and
1308
+ sender_node_id in self.world_masters_node_ids)
1309
+
1310
+ # Assigning a role
1311
+ role_str = self.world.assign_role(profile=profile, is_world_master=is_world_master)
1312
+ if role_str is None:
1313
+ self.err("Unable to determine what role to assign, removing (disconnecting) "
1314
+ + msg.sender)
1315
+ self.__purge(msg.sender)
1316
+ else:
1317
+ role = self.world.ROLE_STR_TO_BITS[role_str] # The role is a bit-wise-interpretable int
1318
+ role = role | (Agent.ROLE_WORLD_MASTER if is_world_master else Agent.ROLE_WORLD_AGENT)
1319
+
1320
+ # Clearing temporary options (if any)
1321
+ dynamic_profile = profile.get_dynamic_profile()
1322
+ keys_to_delete = [key for key in dynamic_profile if key.startswith('tmp_')]
1323
+ for key in keys_to_delete:
1324
+ del dynamic_profile[key]
1325
+
1326
+ if not self.conn.send(msg.sender, channel_trail=None,
1327
+ content={
1328
+ 'world_profile': self.profile.get_all_profile(),
1329
+ 'rendezvous_tag': self.clock.get_cycle(),
1330
+ 'your_role': role,
1331
+ 'agent_actions': self.world.agent_actions
1332
+ },
1333
+ content_type=Msg.WORLD_APPROVAL):
1334
+ self.err("Failed to send world approval, removing (disconnecting) " + msg.sender)
1335
+ self.__purge(msg.sender)
1336
+ else:
1337
+ private_peer_id = profile.get_dynamic_profile()['private_peer_id']
1338
+ private_addr = profile.get_dynamic_profile()['private_peer_addresses']
1339
+ if is_world_master:
1340
+ role = role | Agent.ROLE_WORLD_MASTER
1341
+ self.conn.add_to_world_masters_list(private_peer_id, private_addr, role)
1342
+ else:
1343
+ role = role | Agent.ROLE_WORLD_AGENT
1344
+ self.conn.add_to_world_agents_list(private_peer_id, private_addr, role)
1345
+
1346
+ # Removing from the queue of public interviews
1347
+ # and adding to the private ones (refreshing timer)
1348
+ del self.agents_to_interview[msg.sender] # Removing from public queue
1349
+ self.agents_to_interview[private_peer_id] = [self.clock.get_time(), profile] # Add
1350
+
1351
+ # If the node is an agent, it is time to tell the agent object that a new agent is now known,
1352
+ # and send our profile to the agent that asked for out contact
1353
+ elif self.node_type is Node.AGENT or sender_is_inspector:
1354
+ self.out("Sending agent approval message and profile...")
1355
+
1356
+ if not self.conn.send(msg.sender, channel_trail=None,
1357
+ content={
1358
+ 'my_profile': self.profile.get_all_profile()
1359
+ },
1360
+ content_type=Msg.AGENT_APPROVAL):
1361
+ self.err("Failed to send agent approval, removing (disconnecting) " + msg.sender)
1362
+ self.__purge(msg.sender)
1363
+ else:
1364
+ self.out("Adding known agent and removing it from the interview queue " + msg.sender)
1365
+ if not self.hosted.add_agent(peer_id=msg.sender, profile=profile): # keep "hosted" here
1366
+ self.__purge(msg.sender)
1367
+ else:
1368
+
1369
+ # Removing from the queues
1370
+ del self.agents_to_interview[msg.sender] # Removing from queue
1371
+
1372
+ # (B) received a world-join-approval
1373
+ elif msg.content_type == Msg.WORLD_APPROVAL:
1374
+ self.out("Received a world-join-approval message...")
1375
+
1376
+ # Checking if it is the world we asked for
1377
+ # moreover, it must be on the public network, and this must not be a world-node (of course)
1378
+ # and you must not be already in another world
1379
+ if (not self.conn.is_public(peer_id=msg.sender) or self.node_type is Node.WORLD
1380
+ or msg.sender not in self.agents_expected_to_send_ack or
1381
+ self.profile.get_dynamic_profile()['connections']['world_peer_id'] is not None):
1382
+ self.err("Unexpected world approval, removing (disconnecting) " + msg.sender)
1383
+ self.__purge(msg.sender)
1384
+ else:
1385
+ if msg.sender != self.joining_world_info["world_public_peer_id"]:
1386
+ self.err(f"Unexpected world approval: asked to join "
1387
+ f"{self.joining_world_info['world_public_peer_id']} got approval from {msg.sender} "
1388
+ f"(disconnecting)")
1389
+ self.__purge(msg.sender)
1390
+ else:
1391
+
1392
+ # Getting world profile (includes private addresses) and connecting to the world (privately)
1393
+ self.__join_world(profile=NodeProfile.from_dict(msg.content['world_profile']),
1394
+ role=msg.content['your_role'],
1395
+ agent_actions=msg.content['agent_actions'],
1396
+ rendezvous_tag=msg.content['rendezvous_tag'])
1397
+
1398
+ # (C) received an agent-connect-approval
1399
+ elif msg.content_type == Msg.AGENT_APPROVAL:
1400
+ self.out("Received an agent-connect-approval message...")
1401
+
1402
+ # Checking if it is the agent we asked for
1403
+ if msg.sender not in self.agents_expected_to_send_ack:
1404
+ self.err("Unexpected agent-connect approval, removing (disconnecting) " + msg.sender)
1405
+ self.__purge(msg.sender)
1406
+ else:
1407
+
1408
+ # Adding the agent
1409
+ self.__join_agent(profile=NodeProfile.from_dict(msg.content['my_profile']),
1410
+ peer_id=msg.sender)
1411
+
1412
+ # (D) requested for a profile
1413
+ elif msg.content_type == Msg.PROFILE_REQUEST:
1414
+ self.out("Received a profile request...")
1415
+
1416
+ # If this is a world-node, it expects profile requests only on the public network
1417
+ # if this is not a world or not, we only send profile to agents who are involved in the handshake
1418
+ if ((self.node_type is Node.WORLD and not self.conn.is_public(peer_id=msg.sender)) or
1419
+ (msg.sender not in self.agents_expected_to_send_ack)):
1420
+ self.err("Unexpected profile request, removing (disconnecting) " + msg.sender)
1421
+ self.__purge(msg.sender)
1422
+ else:
1423
+
1424
+ # If a preference was defined, we temporarily add it to the profile
1425
+ if (self.joining_world_info is not None and
1426
+ msg.sender == self.joining_world_info["world_public_peer_id"] and
1427
+ self.joining_world_info["options"] is not None and
1428
+ len(self.joining_world_info["options"]) > 0):
1429
+ my_profile = copy.deepcopy(self.profile)
1430
+ for k, v in self.joining_world_info["options"].items():
1431
+ my_profile.get_dynamic_profile()['tmp_' + str(k)] = v
1432
+ my_profile = my_profile.get_all_profile()
1433
+ else:
1434
+ my_profile = self.profile.get_all_profile()
1435
+
1436
+ # Sending the profile
1437
+ self.out("Sending profile")
1438
+ if not self.conn.send(msg.sender, channel_trail=None,
1439
+ content=my_profile,
1440
+ content_type=Msg.PROFILE):
1441
+ self.err("Failed to send profile, removing (disconnecting) " + msg.sender)
1442
+ self.__purge(msg.sender)
1443
+
1444
+ # (E) the world node received an ADDRESS_UPDATE from an agent
1445
+ elif msg.content_type == Msg.ADDRESS_UPDATE:
1446
+ self.out("Received an address update from " + msg.sender)
1447
+
1448
+ if self.node_type is Node.WORLD and msg.sender in self.world.all_agents:
1449
+ all_addresses = msg.content.get('addresses')
1450
+ if all_addresses and isinstance(all_addresses, list):
1451
+
1452
+ # Update the address both in the connection and in the profile
1453
+ self.conn.set_addresses_in_peer_info(msg.sender, all_addresses)
1454
+ self.world.set_addresses_in_profile(msg.sender, all_addresses)
1455
+ self.out(f"Waiting rendezvous publish after address update from {msg.sender}")
1456
+
1457
+ # (F) got stream data
1458
+ elif msg.content_type == Msg.STREAM_SAMPLE:
1459
+ self.out("Received a stream sample...")
1460
+
1461
+ if self.node_type is Node.AGENT: # Handling the received samples
1462
+ self.agent.get_stream_sample(net_hash=msg.channel, sample_dict=msg.content)
1463
+
1464
+ # Printing messages to screen, if needed (useful when chatting with lone wolves)
1465
+ if interact_mode_opts is not None and "stdout" in interact_mode_opts:
1466
+ net_hash = DataProps.normalize_net_hash(msg.channel)
1467
+ if net_hash in self.agent.known_streams:
1468
+ stream_dict = self.agent.known_streams[net_hash]
1469
+ sys.stdout = interact_mode_opts["stdout"][0] # Output on
1470
+ for name, stream_obj in stream_dict.items():
1471
+ if stream_obj.props.is_text():
1472
+ msg = stream_obj.get(requested_by="print") # Getting message
1473
+ print(f"\n『 {msg} 』") # Printing to screen
1474
+ if stream_obj.props.is_img():
1475
+ img = stream_obj.get(requested_by="print") # Getting image
1476
+ filename = "wolf_img.png"
1477
+ img.save(filename)
1478
+ msg = f"(saved image to {filename})"
1479
+ print(f"\n『 {msg} 』") # Printing to screen
1480
+ print("\n👉 ", end="")
1481
+ sys.stdout = interact_mode_opts["stdout"][1] # Output off
1482
+
1483
+ elif self.node_type is Node.WORLD:
1484
+ self.err("Unexpected stream samples received by this world node, sent by: " + msg.sender)
1485
+ self.__purge(msg.sender)
1486
+
1487
+ # (G) got action request
1488
+ elif msg.content_type == Msg.ACTION_REQUEST:
1489
+ self.out("Received an action request...")
1490
+
1491
+ if self.node_type is Node.AGENT:
1492
+ if msg.sender not in self.agent.all_agents:
1493
+ self.err("Unexpected action request received by a unknown node: " + msg.sender)
1494
+ else:
1495
+ behav = self.agent.behav_lone_wolf \
1496
+ if msg.sender in self.agent.public_agents else self.agent.behav
1497
+ behav.request_action(action_name=msg.content['action_name'],
1498
+ args=msg.content['args'],
1499
+ signature=msg.sender,
1500
+ timestamp=self.clock.get_time(),
1501
+ uuid=msg.content['uuid'])
1502
+
1503
+ elif self.node_type is Node.WORLD:
1504
+ self.err("Unexpected action request received by this world node, sent by: " + msg.sender)
1505
+ self.__purge(msg.sender)
1506
+
1507
+ # (H) got role suggestion
1508
+ elif msg.content_type == Msg.ROLE_SUGGESTION:
1509
+ self.out("Received a role suggestion/new role...")
1510
+
1511
+ if self.node_type is Node.AGENT:
1512
+ if msg.sender == self.conn.get_world_peer_id():
1513
+ new_role_indication = msg.content
1514
+ if new_role_indication['peer_id'] == self.get_world_peer_id():
1515
+ self.agent.accept_new_role(new_role_indication['role'])
1516
+
1517
+ self.agent.behav.update_wildcard("<agent>", f"{self.get_world_peer_id()}")
1518
+ self.agent.behav.update_wildcard("<world>", f"{msg.sender}")
1519
+
1520
+ elif self.node_type is Node.WORLD:
1521
+ if msg.sender in self.world.world_masters:
1522
+ for role_suggestion in msg.content:
1523
+ self.world.set_role(peer_id=role_suggestion['peer_id'], role=role_suggestion['role'])
1524
+
1525
+ # (I) got request to alter the HSM
1526
+ elif msg.content_type == Msg.HSM:
1527
+ self.out("Received a request to alter the HSM...")
1528
+
1529
+ if self.node_type is Node.AGENT:
1530
+ if msg.sender in self.agent.world_masters: # This must be coherent with what we do in set_role
1531
+ ret = getattr(self.agent.behav, msg.content['method'])(*msg.content['args'])
1532
+ if not ret:
1533
+ self.err(f"Cannot run HSM action named {msg.content['method']} with args "
1534
+ f"{msg.content['args']}")
1535
+ else:
1536
+ self.err("Only world-master can alter HSMs of other agents: " + msg.sender) # No need to purge
1537
+
1538
+ elif self.node_type is Node.WORLD:
1539
+ self.err("Unexpected request to alter the HSM received by this world node, sent by: " + msg.sender)
1540
+ self.__purge(msg.sender)
1541
+
1542
+ # (J) misc
1543
+ elif msg.content_type == Msg.MISC:
1544
+ self.out("Received a misc message...")
1545
+ self.out(msg.content)
1546
+
1547
+ # (K) got a request to re-download the CV from the root server
1548
+ elif msg.content_type == Msg.GET_CV_FROM_ROOT:
1549
+ self.out("Received a notification to re-download the CV...")
1550
+
1551
+ # Downloading CV
1552
+ self.profile.update_cv(self.get_cv())
1553
+
1554
+ # Re-downloading token (it will include the new CV hash)
1555
+ self.get_node_token(peer_ids=[self.get_public_peer_id(), self.get_world_peer_id()])
1556
+
1557
+ # (L) got one or more badge suggestions
1558
+ elif msg.content_type == Msg.BADGE_SUGGESTIONS:
1559
+ self.out("Received badge suggestions...")
1560
+
1561
+ if self.node_type is Node.WORLD:
1562
+ for badge_dict in msg.content:
1563
+
1564
+ # Right now, we accept all the suggestions
1565
+ self.world.add_badge(**badge_dict) # Adding to the list of badges
1566
+ elif self.node_type is Node.AGENT:
1567
+ self.err("Receiving badge suggestions is not expected for an agent node")
1568
+
1569
+ # (M) got a special connection/presence message for an inspector
1570
+ elif msg.content_type == Msg.INSPECT_ON:
1571
+ self.out("Received an inspector-activation message...")
1572
+
1573
+ if sender_is_inspector:
1574
+ self.inspector_activated = True
1575
+ self.inspector_peer_id = msg.sender
1576
+ print("Inspector activated")
1577
+ else:
1578
+ self.err("Inspector-activation message was not sent by the expected inspector node ID")
1579
+ self.__purge(msg.sender)
1580
+
1581
+ # (N) got a command from an inspector
1582
+ elif msg.content_type == Msg.INSPECT_CMD:
1583
+ self.out("Received a command from the inspector...")
1584
+
1585
+ if sender_is_inspector and self.inspector_activated:
1586
+ self.__handle_inspector_command(msg.content['cmd'], msg.content['arg'])
1587
+ else:
1588
+ self.err("Inspector command was not sent by the expected inspector node ID "
1589
+ "or the inspector was not yet activated (Msg.INSPECT_ON not received yet)")
1590
+ self.__purge(msg.sender)
1591
+
1592
+ self.__interview_clean()
1593
+ self.__connected_without_ack_clean()
1594
+
1595
+ def __join_world(self, profile: NodeProfile, role: int,
1596
+ agent_actions: str | None, rendezvous_tag: int):
1597
+ """Performs the actual operation of joining a world after receiving confirmation.
1598
+
1599
+ Args:
1600
+ profile: The profile of the world to join.
1601
+ role: The role assigned to the agent in the world (int).
1602
+ agent_actions: A string of code defining the agent's actions.
1603
+ rendezvous_tag: The rendezvous tag from the world's profile.
1604
+
1605
+ Returns:
1606
+ True if the join operation is successful, otherwise False.
1607
+ """
1608
+ addresses = profile.get_dynamic_profile()['private_peer_addresses']
1609
+ world_public_peer_id = profile.get_dynamic_profile()['peer_id']
1610
+ self.out(f"Actually joining world, role will be {role}")
1611
+
1612
+ # Connecting to the world (private)
1613
+ # notice that we also communicate the world node private peer ID to the connection manager,
1614
+ # to avoid filtering it out when updating pools
1615
+ peer_id = self.ask_to_get_in_touch(addresses=addresses, public=False,
1616
+ before_updating_pools_fcn=self.conn.set_world)
1617
+
1618
+ if peer_id is not None:
1619
+
1620
+ # Relay reservation logic for non-public peers
1621
+ if not self.conn.p2p_world.is_public and self.conn.p2p_world.relay_is_enabled:
1622
+ self.out("Node is not publicly reachable. Attempting to reserve a slot on the world's private network.")
1623
+ try:
1624
+ expiry_utc = self.conn.p2p_world.reserve_on_relay(peer_id)
1625
+ self.relay_reservation_expiry = (
1626
+ datetime.fromisoformat(expiry_utc.replace('Z', '+00:00')))
1627
+ self.out(f"Reserved relay slot. Expires at "
1628
+ f"{self.relay_reservation_expiry.strftime('%Y-%m-%d %H:%M:%S')} UTC")
1629
+
1630
+ self.out("Fetching updated address list from transport layer...")
1631
+ complete_private_addrs = self.conn.p2p_world.get_node_addresses()
1632
+
1633
+ # Update the profile with this definitive list (IN-PLACE)
1634
+ address_list = self.profile.get_dynamic_profile()['private_peer_addresses']
1635
+ address_list.clear()
1636
+ address_list.extend(complete_private_addrs)
1637
+
1638
+ self.out("Notifying world of the complete updated address list...")
1639
+ self.conn.send(peer_id, channel_trail=None,
1640
+ content_type=Msg.ADDRESS_UPDATE,
1641
+ content={'addresses': complete_private_addrs})
1642
+ except Exception as e:
1643
+ self.err(f"An error occurred during relay reservation: {e}.")
1644
+
1645
+ # Subscribing to the world rendezvous topic, from which we will get fresh information
1646
+ # about the world agents and masters
1647
+ self.out("Subscribing to the world-members topic...")
1648
+ if not self.conn.subscribe(peer_id, channel=f"{peer_id}::ps:rv"): # Special rendezvous (ps:rv)
1649
+ self.leave(peer_id) # If subscribing fails, we quit everything (safer)
1650
+ return False
1651
+
1652
+ # Killing the public connection to the world node
1653
+ self.out("Disconnecting from the public world network (since we joined the private one)")
1654
+ self.__purge(world_public_peer_id)
1655
+
1656
+ # Removing the private world peer id from the list of connected-but-not-managed peer
1657
+ del self.agents_expected_to_send_ack[peer_id]
1658
+
1659
+ # Subscribing to all the other world topics, from which we will get fresh information
1660
+ # about the streams
1661
+ self.out("Subscribing to the world-streams topics...")
1662
+ dynamic_profile = profile.get_dynamic_profile()
1663
+ list_of_props = []
1664
+ list_of_props += dynamic_profile['streams'] if dynamic_profile['streams'] is not None else []
1665
+ list_of_props += dynamic_profile['proc_outputs'] if dynamic_profile['proc_outputs'] is not None else []
1666
+
1667
+ if not self.agent.add_compatible_streams(peer_id, list_of_props, buffered=False, public=False):
1668
+ self.leave(peer_id)
1669
+ return False
1670
+
1671
+ # Setting actions
1672
+ if agent_actions is not None and len(agent_actions) > 0:
1673
+
1674
+ # Checking code
1675
+ if not Node.__analyze_code(agent_actions):
1676
+ self.err("Invalid agent actions code (syntax errors or unsafe code) was provided by the world, "
1677
+ "blocking the join operation")
1678
+ return False
1679
+
1680
+ # Creating a new agent with the received actions
1681
+ mod = types.ModuleType("dynamic_module")
1682
+ exec(agent_actions, mod.__dict__)
1683
+ sys.modules["dynamic_module"] = mod
1684
+ new_agent = mod.WAgent(proc=None)
1685
+
1686
+ # Cloning attributes of the existing agent
1687
+ for key, value in self.agent.__dict__.items():
1688
+ if hasattr(new_agent, key): # This will skip ROLE_BITS_TO_STR, CUSTOM_ROLES, etc...
1689
+ setattr(new_agent, key, value)
1690
+
1691
+ # Telling the FSM that actions are related to this new agent
1692
+ new_agent.behav.set_actionable(new_agent)
1693
+ new_agent.behav_lone_wolf.set_actionable(new_agent)
1694
+
1695
+ # Setting up roles
1696
+ roles = profile.get_dynamic_profile()['world_roles_fsm'].keys()
1697
+ new_agent.CUSTOM_ROLES = roles
1698
+ new_agent.augment_roles()
1699
+
1700
+ # Setting up world stats
1701
+ world_stats_dynamic_by_peer = profile.get_dynamic_profile()['world_stats_dynamic']
1702
+ if world_stats_dynamic_by_peer:
1703
+ new_agent.STATS_DYNAMIC_SENT_BY_PEER.clear()
1704
+ new_agent.STATS_DYNAMIC_SENT_BY_PEER.update(world_stats_dynamic_by_peer) # in-place
1705
+ new_agent.clear_stats()
1706
+
1707
+ # Updating node-level references
1708
+ old_agent = self.agent
1709
+ self.agent = new_agent
1710
+ self.hosted = new_agent
1711
+ else:
1712
+ old_agent = self.agent
1713
+
1714
+ # Saving the world profile
1715
+ self.agent.world_profile = profile
1716
+
1717
+ # Setting the assigned role and default behavior (do it after having recreated the new agent object)
1718
+ self.agent.accept_new_role(role) # Do this after having done 'self.agent.world_profile = profile'
1719
+
1720
+ # Updating wildcards
1721
+ self.agent.behav.update_wildcard("<agent>", f"{self.get_world_peer_id()}")
1722
+ self.agent.behav.update_wildcard("<world>", f"{peer_id}")
1723
+ self.agent.behav.add_wildcards(old_agent.behav_wildcards)
1724
+
1725
+ # Telling the connection manager the info needed to discriminate peers (getting them from the world profile)
1726
+ # notice that the world node private ID was already told to the connection manager (see a few lines above)
1727
+ self.out(f"Rendezvous tag received with profile: {rendezvous_tag} "
1728
+ f"(in conn pool: {self.conn.rendezvous_tag})")
1729
+ if self.conn.rendezvous_tag < rendezvous_tag:
1730
+ self.conn.rendezvous_tag = rendezvous_tag
1731
+ num_world_masters = len(dynamic_profile['world_summary']['world_masters']) \
1732
+ if dynamic_profile['world_summary']['world_masters'] is not None else 'none'
1733
+ num_world_agents = len(dynamic_profile['world_summary']['world_agents']) \
1734
+ if dynamic_profile['world_summary']['world_agents'] is not None else 'none'
1735
+ self.out(f"Rendezvous from profile (tag: {rendezvous_tag}), world masters: {num_world_masters}")
1736
+ self.out(f"Rendezvous from profile (tag: {rendezvous_tag}), world agents: {num_world_agents}")
1737
+ self.conn.set_world_masters_list(dynamic_profile['world_summary']['world_masters'])
1738
+ self.conn.set_world_agents_list(dynamic_profile['world_summary']['world_agents'])
1739
+
1740
+ # Updating our profile to set the world we are in
1741
+ self.profile.get_dynamic_profile()['connections']['world_peer_id'] = peer_id
1742
+ self.profile.mark_change_in_connections()
1743
+
1744
+ print("Handshake completed, world joined!")
1745
+ return True
1746
+ else:
1747
+ return False
1748
+
1749
+ def __join_agent(self, profile: NodeProfile, peer_id: str):
1750
+ """Adds a new known agent after receiving an approval message.
1751
+
1752
+ Args:
1753
+ profile: The profile of the agent to join.
1754
+ peer_id: The peer ID of the agent.
1755
+
1756
+ Returns:
1757
+ True if the agent is successfully added, otherwise False.
1758
+ """
1759
+ self.out("Adding known agent " + peer_id)
1760
+ if not self.agent.add_agent(peer_id=peer_id, profile=profile):
1761
+ self.__purge(peer_id)
1762
+ return False
1763
+
1764
+ del self.agents_expected_to_send_ack[peer_id]
1765
+ return True
1766
+
1767
+ def __interview_enqueue(self, peer_id: str):
1768
+ """Adds a newly connected peer to the queue of agents to be interviewed.
1769
+
1770
+ Args:
1771
+ peer_id: The peer ID of the agent to interview.
1772
+
1773
+ Returns:
1774
+ True if the agent is successfully enqueued, otherwise False.
1775
+ """
1776
+
1777
+ # If the peer_id is not in the same world were we are, we early stop the interview process
1778
+ if (not self.conn.is_public(peer_id) and peer_id not in self.conn.world_agents_list and
1779
+ peer_id not in self.conn.world_masters_list and peer_id != self.conn.world_node_peer_id):
1780
+ self.out(f"Interview failed: "
1781
+ f"peer ID {peer_id} is not in the world agents/masters list, and it is not the world node")
1782
+ return False
1783
+
1784
+ # Ask for the profile
1785
+ ret = self.conn.send(peer_id, channel_trail=None,
1786
+ content_type=Msg.PROFILE_REQUEST, content=None)
1787
+ if not ret:
1788
+ self.out(f"Interview failed: "
1789
+ f"unable to send a profile request to peer ID {peer_id}")
1790
+ return False
1791
+
1792
+ # Put the agent in the list of agents to interview
1793
+ self.agents_to_interview[peer_id] = [self.clock.get_time(), None] # Peer ID -> [time, profile]; no profile yet
1794
+ return True
1795
+
1796
+ def __interview_check_profile(self, peer_id: str, node_id: str, profile: NodeProfile):
1797
+ """Checks if a received profile is acceptable and valid.
1798
+
1799
+ Args:
1800
+ peer_id: The peer ID of the node that sent the profile.
1801
+ node_id: The node ID of the node that sent the profile.
1802
+ profile: The NodeProfile object to be checked.
1803
+
1804
+ Returns:
1805
+ True if the profile is acceptable, otherwise False.
1806
+ """
1807
+
1808
+ # If the node ID was not on the list of allowed ones (if the list exists), then stop it
1809
+ # notice that we do not get the node ID from the profile, but from outside (it comes from the token, so safe)
1810
+ if ((self.allowed_node_ids is not None and node_id not in self.allowed_node_ids) or
1811
+ (peer_id not in self.agents_to_interview)):
1812
+ self.out(f"Profile of f{peer_id} not in the list of agents to interview or its node ID is not allowed")
1813
+ return False
1814
+ else:
1815
+
1816
+ # Getting the parts of profile needed
1817
+ eval_static_profile = profile.get_static_profile()
1818
+ eval_dynamic_profile = profile.get_dynamic_profile()
1819
+ my_dynamic_profile = self.profile.get_dynamic_profile()
1820
+
1821
+ # Checking if CV was altered
1822
+ cv_hash = self.conn.get_cv_hash_from_last_token(peer_id)
1823
+ sanity_ok, pairs_of_hashes = profile.verify_cv_hash(cv_hash)
1824
+ if not sanity_ok:
1825
+ self.out(f"The CV in the profile of f{peer_id} failed the sanity check {pairs_of_hashes},"
1826
+ f" {profile.get_cv()}")
1827
+ return False
1828
+
1829
+ # Determining type of agent, checking the connection pools
1830
+ role = self.conn.get_role(peer_id)
1831
+
1832
+ if role & 1 == 0:
1833
+
1834
+ # Ensuring that the interviewed agent is out of every world
1835
+ # (if it were in the same world in which we are, it would connect in a private manner) and
1836
+ # possibly fulfilling the optional constraint of accepting only certified agent,
1837
+ # then asking the hosted entity for additional custom evaluation
1838
+ if (eval_dynamic_profile['connections']['world_peer_id'] is None and
1839
+ (not self.only_certified_agents or eval_static_profile['certified'] is True)):
1840
+ return self.hosted.evaluate_profile(role, profile)
1841
+ else:
1842
+ self.out(f"Peer f{peer_id} is already living in a world, of it is not certified "
1843
+ f"and maybe I expect certified only")
1844
+ return False
1845
+ else:
1846
+
1847
+ if self.node_type is Node.AGENT:
1848
+
1849
+ # Ensuring that the interviewed agent is in the same world where we are and
1850
+ # possibly fulfilling the optional constraint of accepting only certified agent
1851
+ if (eval_dynamic_profile['connections']['world_peer_id'] is not None and
1852
+ eval_dynamic_profile['connections']['world_peer_id'] ==
1853
+ my_dynamic_profile['connections']['world_peer_id'] and
1854
+ (not self.only_certified_agents or 'certified' in eval_static_profile and
1855
+ eval_static_profile['certified'] is True)):
1856
+ return self.hosted.evaluate_profile(role, profile)
1857
+ else:
1858
+ self.out(f"Peer f{peer_id} is living in a different world, of it is not certified "
1859
+ f"and maybe I expect certified only")
1860
+ return False
1861
+
1862
+ elif self.node_type is Node.WORLD:
1863
+
1864
+ # If this node hosts a world, we do not expect to interview agents in the private world connection,
1865
+ # so something went wrong here, let's reject it
1866
+ self.out(f"Peer f{peer_id} sent a profile in the private network, unexpected")
1867
+ return False
1868
+
1869
+ def __interview_clean(self):
1870
+ """Removes outdated or timed-out interview requests from the queue."""
1871
+ cur_time = self.clock.get_time()
1872
+ agents_to_remove = []
1873
+ for peer_id, (profile_time, profile) in self.agents_to_interview.items():
1874
+
1875
+ # Checking timeout
1876
+ if (cur_time - profile_time) > self.interview_timeout:
1877
+ self.out("Removing (disconnecting) due to timeout in interview queue: " + peer_id)
1878
+ agents_to_remove.append(peer_id)
1879
+
1880
+ # Updating
1881
+ for peer_id in agents_to_remove:
1882
+ self.__purge(peer_id) # This will also remove the peer from the queue of peers to interview
1883
+
1884
+ def __connected_without_ack_clean(self):
1885
+ """Removes connected peers from the queue if they haven't sent an acknowledgment within the timeout period."""
1886
+ cur_time = self.clock.get_time()
1887
+ agents_to_remove = []
1888
+ for peer_id, connection_time in self.agents_expected_to_send_ack.items():
1889
+
1890
+ # Checking timeout
1891
+ if (cur_time - connection_time) > self.connect_without_ack_timeout:
1892
+ self.out("Removing (disconnecting) due to timeout in the connected-without-ack queue: " + peer_id)
1893
+ agents_to_remove.append(peer_id)
1894
+
1895
+ # Updating
1896
+ for peer_id in agents_to_remove:
1897
+ self.__purge(peer_id) # This will also remove the peer from the queue of in the connected-without-ack queue
1898
+
1899
+ def __purge(self, peer_id: str):
1900
+ """Removes a peer from all relevant connection lists and queues.
1901
+
1902
+ Args:
1903
+ peer_id: The peer ID of the node to purge.
1904
+ """
1905
+ self.hosted.remove_agent(peer_id)
1906
+ self.conn.remove(peer_id)
1907
+
1908
+ # Clearing also the contents of the list of interviews
1909
+ if peer_id in self.agents_to_interview:
1910
+ del self.agents_to_interview[peer_id]
1911
+
1912
+ # Clearing the temporary list of connected agents
1913
+ if peer_id in self.agents_expected_to_send_ack:
1914
+ del self.agents_expected_to_send_ack[peer_id]
1915
+
1916
+ def __root(self, api: str, payload: dict):
1917
+ """Sends a POST request to the root server's API endpoint.
1918
+
1919
+ Args:
1920
+ api: The API endpoint to send the request to.
1921
+ payload: The data to be sent in the request body.
1922
+
1923
+ Returns:
1924
+ The 'data' field from the server's JSON response.
1925
+ """
1926
+ response_fields = ["state", "flags", "data"]
1927
+
1928
+ try:
1929
+ api = self.root_endpoint + ("/" if self.root_endpoint[-1] != "/" and api[0] != "/" else "") + api
1930
+ payload["node_token"] = self.node_token # Adding token to let the server verify
1931
+ response = requests.post(api,
1932
+ json=payload,
1933
+ headers={"Content-Type": "application/json"})
1934
+
1935
+ if response.status_code == 200:
1936
+ ret = response.json()
1937
+ if response_fields is not None:
1938
+ for field in response_fields:
1939
+ if field not in ret:
1940
+ raise GenException(f"Missing key '{field}' in the response to {api}: {ret}")
1941
+ else:
1942
+ raise GenException(f"Request {api} failed with status code {response.status_code}")
1943
+ except Exception as e:
1944
+ self.err(f"An error occurred while making the POST request: {e}")
1945
+ raise GenException(f"An error occurred while making the POST request: {e}")
1946
+
1947
+ if ret['state']['code'] != "ok":
1948
+ raise GenException("[" + api + "] " + ret['state']['message'])
1949
+
1950
+ return ret['data']
1951
+
1952
+ @staticmethod
1953
+ def __analyze_code(file_in_memory):
1954
+ """Analyzes a string of Python code for dangerous or unsafe functions and modules.
1955
+
1956
+ Args:
1957
+ file_in_memory: The string of Python code to analyze.
1958
+
1959
+ Returns:
1960
+ True if the code is considered safe, otherwise False.
1961
+ """
1962
+ dangerous_functions = {"eval", "exec", "compile", "system", "__import__", "input"}
1963
+ dangerous_modules = {"subprocess"}
1964
+
1965
+ def is_suspicious(ast_node):
1966
+
1967
+ # Detect bare function calls like eval(...)
1968
+ if isinstance(ast_node, ast.Call):
1969
+ # case: eval(...) (ast.Name)
1970
+ if isinstance(ast_node.func, ast.Name):
1971
+ return ast_node.func.id in dangerous_functions
1972
+ # case: something.eval(...) (ast.Attribute)
1973
+ elif isinstance(ast_node.func, ast.Attribute):
1974
+ attr_name = ast_node.func.attr
1975
+ # 1) If attribute name is one of the dangerous_functions, only flag it
1976
+ # if the object is a suspicious module (os, subprocess, etc.)
1977
+ if attr_name in dangerous_functions:
1978
+ value = ast_node.func.value
1979
+ # example: os.system(...) => ast.Name(id='os')
1980
+ if isinstance(value, ast.Name):
1981
+ if value.id in dangerous_modules:
1982
+ return True
1983
+ # example: package.subpackage.func(...) => ast.Attribute
1984
+ # check top-level name if possible: walk down to the leftmost Name
1985
+ left = value
1986
+ while isinstance(left, ast.Attribute):
1987
+ left = left.value
1988
+ if isinstance(left, ast.Name) and left.id in dangerous_modules:
1989
+ return True
1990
+ # 2) Also catch explicit module imports used directly:
1991
+ # subprocess.run(...), os.system(...), etc.
1992
+ if isinstance(ast_node.func.value, ast.Name):
1993
+ if ast_node.func.value.id in dangerous_modules:
1994
+ # if the module is suspicious, any attribute call is risky
1995
+ return True
1996
+
1997
+ # Detect imports
1998
+ if isinstance(ast_node, (ast.Import, ast.ImportFrom)):
1999
+ for alias in ast_node.names:
2000
+ if alias.name.split('.')[0] in dangerous_modules:
2001
+ return True
2002
+
2003
+ return False
2004
+
2005
+ try:
2006
+ tree = ast.parse(file_in_memory)
2007
+ except SyntaxError:
2008
+ return False
2009
+
2010
+ for _ast_node in ast.walk(tree):
2011
+ if is_suspicious(_ast_node):
2012
+ return False
2013
+
2014
+ return True
2015
+
2016
+ def __handle_inspector_command(self, cmd: str, arg):
2017
+ """Handles commands received from an inspector node.
2018
+
2019
+ Args:
2020
+ cmd: The command string.
2021
+ arg: The argument for the command.
2022
+ """
2023
+ self.out(f"Handling inspector message {cmd}, with arg {arg}")
2024
+ print(f"Handling inspector message {cmd}, with arg {arg}")
2025
+
2026
+ if arg is not None and not isinstance(arg, str):
2027
+ self.err(f"Expecting a string argument from the inspector!")
2028
+ else:
2029
+ if cmd == "ask_to_join_world":
2030
+ print(f"Inspector asked to join world: {arg}")
2031
+ self.ask_to_join_world(node_name=arg)
2032
+ elif cmd == "ask_to_get_in_touch":
2033
+ print(f"Inspector asked to get in touch with an agent: {arg}")
2034
+ self.ask_to_get_in_touch(node_name=arg, public=True)
2035
+ elif cmd == "leave":
2036
+ print(f"Inspector asked to leave an agent: {arg}")
2037
+ self.leave(arg)
2038
+ elif cmd == "leave_world":
2039
+ print(f"Inspector asked to leave the current world")
2040
+ self.leave_world()
2041
+ elif cmd == "pause":
2042
+ print("Inspector asked to pause")
2043
+ self.__inspector_told_to_pause = True
2044
+ elif cmd == "play":
2045
+ print("Inspector asked to play")
2046
+ self.__inspector_told_to_pause = False
2047
+ elif cmd == "save":
2048
+ print("Inspector asked to save")
2049
+ self.hosted.save(arg)
2050
+ else:
2051
+ self.err("Unknown inspector command")
2052
+
2053
+ def __send_to_inspector(self):
2054
+ """Sends status updates and data to the connected inspector node."""
2055
+
2056
+ # Collecting console
2057
+ f = self._output_messages_last_pos - self._output_messages_count + 1 # Included
2058
+ t = self._output_messages_last_pos # Included
2059
+ ff = -1
2060
+ tt = -1
2061
+ if t >= 0 > f: # If there is something, and we incurred in the circular organization (t: valid; f: negative)
2062
+ ff = len(self._output_messages) + f # Included
2063
+ tt = len(self._output_messages) - 1 # Included
2064
+ f = 0
2065
+ elif t < 0: # If there are no messages at all (t: -1; f: 0 - due to the way we initialized class attributes)
2066
+ f = -1
2067
+ t = -1
2068
+ console = {'output_messages': self._output_messages[ff:tt+1] + self._output_messages[f:t+1]}
2069
+
2070
+ # Collecting the HSM
2071
+ if self.__inspector_cache['behav'] != self.hosted.behav:
2072
+ self.__inspector_cache['behav'] = self.hosted.behav
2073
+ behav = str(self.hosted.behav)
2074
+ else:
2075
+ behav = None
2076
+
2077
+ # Collecting status of the HSM
2078
+ if self.hosted.behav is not None:
2079
+ _behav = self.hosted.behav
2080
+ state = _behav.get_state().id if _behav.get_state() is not None else None
2081
+ action = _behav.get_action().id if _behav.get_action() is not None else None
2082
+ behav_status = {'state': state, 'action': action,
2083
+ 'state_with_action': _behav.get_state().has_action()
2084
+ if (state is not None) else False}
2085
+ else:
2086
+ behav_status = None
2087
+
2088
+ # Collecting known agents
2089
+ if self.__inspector_cache['all_agents_count'] != len(self.hosted.all_agents):
2090
+ self.__inspector_cache['all_agents_count'] = len(self.hosted.all_agents)
2091
+ all_agents_profiles = {k: v.get_all_profile() for k, v in self.hosted.all_agents.items()}
2092
+
2093
+ # Inspector expects also to have access to the profile of the world,
2094
+ # so we patch this thing by adding it here
2095
+ if self.hosted.in_world() and self.conn.world_node_peer_id is not None:
2096
+ all_agents_profiles[self.conn.world_node_peer_id] = self.hosted.world_profile.get_all_profile()
2097
+ else:
2098
+ all_agents_profiles = None
2099
+
2100
+ # Collecting known streams info
2101
+ if self.__inspector_cache['known_streams_count'] != len(self.hosted.known_streams):
2102
+ self.__inspector_cache['known_streams_count'] = len(self.hosted.known_streams)
2103
+ known_streams_props = {(k + "-" + name): v.get_props().to_dict() for k, stream_dict in
2104
+ self.hosted.known_streams.items() for name, v in stream_dict.items()}
2105
+ else:
2106
+ known_streams_props = None
2107
+
2108
+ # Packing console, HSM status, and possibly HSM
2109
+ console_behav_status_and_behav = {'console': console,
2110
+ 'behav': behav,
2111
+ 'behav_status': behav_status,
2112
+ 'all_agents_profiles': all_agents_profiles,
2113
+ 'known_streams_props': known_streams_props}
2114
+
2115
+ # Sending console, HSM status, and possibly HSM to the inspector
2116
+ if not self.conn.send(self.inspector_peer_id, channel_trail=None,
2117
+ content_type=Msg.CONSOLE_AND_BEHAV_STATUS,
2118
+ content=console_behav_status_and_behav):
2119
+ self.err("Failed to send data to the inspector")
2120
+
2121
+ # Sending stream data (not pubsub) to the inspector
2122
+ my_peer_ids = (self.get_public_peer_id(), self.get_world_peer_id())
2123
+ for net_hash, streams_dict in self.hosted.known_streams.items():
2124
+ peer_id = DataProps.peer_id_from_net_hash(net_hash)
2125
+
2126
+ # Preparing sample dict
2127
+ something_to_send = False
2128
+ content = {name: {} for name in streams_dict.keys()}
2129
+ for name, stream in streams_dict.items():
2130
+ data = stream.get(requested_by="__send_to_inspector")
2131
+
2132
+ if data is not None:
2133
+ something_to_send = True
2134
+
2135
+ self.hosted.deb(f"[__send_to_inspector] Preparing to send stream samples from {net_hash}, {name}")
2136
+ content[(peer_id + "|" + name) if peer_id not in my_peer_ids else name] = \
2137
+ {'data': data, 'data_tag': stream.get_tag(), 'data_uuid': stream.get_uuid()}
2138
+
2139
+ # Checking if there is something valid in this group of streams to send to inspector
2140
+ if not something_to_send:
2141
+ self.hosted.deb(f"[__send_to_inspector] No stream samples to send to inspector for {net_hash}, "
2142
+ f"all internal streams returned None")
2143
+ continue
2144
+
2145
+ self.hosted.deb(f"[__send_to_inspector] Sending samples of {net_hash} by direct message, to inspector")
2146
+ name_or_group = DataProps.name_or_group_from_net_hash(net_hash)
2147
+ if not self.conn.send(self.inspector_peer_id, channel_trail=name_or_group,
2148
+ content_type=Msg.STREAM_SAMPLE, content=content):
2149
+ self.err(f"Failed to send stream sample data to the inspector (hash: {net_hash})")
2150
+
2151
+
2152
+ class NodeSynchronizer:
2153
+ DEBUG = True
2154
+
2155
+ def __init__(self):
2156
+ """Initializes a new instance of the NodeSynchronizer class."""
2157
+ self.nodes = []
2158
+ self.agent_nodes = {}
2159
+ self.world_node = None # Added to allow get_console() to access the world node from server.py (synch only)
2160
+ self.streams = {}
2161
+ self.world = None
2162
+ self.world_masters = set()
2163
+ self.world_masters_node_ids = None
2164
+ self.agent_name_to_profile = {}
2165
+ self.clock = Clock()
2166
+ self.synch_cycle = -1
2167
+ self.synch_cycles = -1
2168
+
2169
+ # Visualization-related attributes
2170
+ self.using_server = False
2171
+ self.server_checkpoints = None
2172
+ self.skip_clear_for = 0
2173
+ self.step_event = None # Event that triggers a new step (manipulated by the server)
2174
+ self.wait_event = None # Event that triggers a new "wait-for-step-event" case (manipulated by the server)
2175
+ self.next_checkpoint = 0
2176
+ self.server_checkpoints = None
2177
+ self.gap = 0. # Seconds
2178
+
2179
+ def add_node(self, node: Node):
2180
+ """Adds a new node to the synchronizer.
2181
+
2182
+ Args:
2183
+ node: The node to add.
2184
+ """
2185
+ self.nodes.append(node)
2186
+
2187
+ if node.node_type == Node.AGENT:
2188
+ self.agent_nodes[node.agent.get_name()] = node
2189
+ if self.world_masters_node_ids is not None:
2190
+ if node.node_id in self.world_masters_node_ids:
2191
+ self.world_masters.add(node.agent.get_name())
2192
+ self.agent_name_to_profile[node.agent.get_name()] = node.agent.get_profile()
2193
+ elif node.node_type == Node.WORLD:
2194
+ self.world_node = node
2195
+ self.world = node.world
2196
+ self.world_masters_node_ids = node.world_masters_node_ids
2197
+ if self.world_masters_node_ids is None:
2198
+ self.world_masters_node_ids = set()
2199
+ for node in self.nodes:
2200
+ if node.node_id in self.world_masters_node_ids:
2201
+ self.world_masters.add(node.agent.get_name())
2202
+ node.debug_server_running = True
2203
+
2204
+ def run(self, synch_cycles: int | None = None):
2205
+ """Starts the main execution loop for the node.
2206
+
2207
+ Args:
2208
+ synch_cycles: The number of clock cycles to run the loop for. If None, runs indefinitely.
2209
+ """
2210
+ if self.world is None:
2211
+ raise GenException("Missing world node")
2212
+
2213
+ # External events
2214
+ if self.using_server:
2215
+ self.step_event = threading.Event()
2216
+ self.wait_event = threading.Event()
2217
+
2218
+ # Main loop
2219
+ self.synch_cycles = synch_cycles
2220
+ self.synch_cycle = 0
2221
+
2222
+ try:
2223
+ while True:
2224
+
2225
+ # In server mode, we wait for an external event to go ahead (step_event.set())
2226
+ if self.using_server:
2227
+ self.wait_event.set()
2228
+ self.step_event.wait()
2229
+ self.wait_event.clear()
2230
+
2231
+ state_changed = False
2232
+ world_node = None
2233
+ for node in self.nodes:
2234
+ if node.node_type == Node.AGENT:
2235
+ node.run(cycles=1)
2236
+ if self.gap > 0.:
2237
+ time.sleep(self.gap)
2238
+ state_changed = state_changed or node.agent.behav.get_state_changed()
2239
+ else:
2240
+ world_node = node
2241
+ if world_node is not None:
2242
+ world_node.run(cycles=1)
2243
+ if self.gap > 0.:
2244
+ time.sleep(self.gap)
2245
+
2246
+ if NodeSynchronizer.DEBUG and state_changed:
2247
+ for node in self.nodes:
2248
+ if node.node_type == Node.AGENT:
2249
+ print(f"[DEBUG NODE SYNCHRONIZER] {node.agent.get_name()} "
2250
+ f"state: {node.agent.behav.get_state_name()}")
2251
+
2252
+ # Matching checkpoints
2253
+ if self.server_checkpoints is not None and self.server_checkpoints["current"] >= 0:
2254
+ self.server_checkpoints["matched"] = -1
2255
+ checkpoint = self.server_checkpoints["checkpoints"][self.server_checkpoints["current"]]
2256
+ agent = checkpoint["agent"]
2257
+ state = checkpoint["state"] if "state" in checkpoint else None
2258
+
2259
+ if agent not in self.nodes:
2260
+ raise GenException(f"Unknown agent in the checkpoint list: {agent}")
2261
+ behav = self.nodes[agent].agent.behav
2262
+ if not (state is None or state in behav.states):
2263
+ raise GenException(f"Unknown state in the checkpoint list: {state}")
2264
+
2265
+ if state is None or behav.state == state:
2266
+ if "skip" not in checkpoint:
2267
+ self.server_checkpoints["matched"] = self.server_checkpoints["current"]
2268
+ self.server_checkpoints["current"] += 1
2269
+ if self.server_checkpoints["current"] >= len(self.server_checkpoints["checkpoints"]):
2270
+ self.server_checkpoints["current"] = -1 # This means: no more checkpoints
2271
+ else:
2272
+ checkpoint["skip"] -= 1
2273
+ if checkpoint["skip"] <= 0:
2274
+ self.server_checkpoints["current"] += 1
2275
+ if self.server_checkpoints["current"] >= len(self.server_checkpoints["checkpoints"]):
2276
+ self.server_checkpoints["current"] = -1 # This means: no more checkpoints
2277
+
2278
+ # In step mode, we clear the external event to be able to wait for a new one
2279
+ if self.using_server:
2280
+ if self.skip_clear_for == 0:
2281
+ self.step_event.clear()
2282
+ elif self.skip_clear_for == -2: # Infinite play
2283
+ pass
2284
+ elif self.skip_clear_for == -1: # Play until next state
2285
+ if state_changed:
2286
+ self.step_event.clear()
2287
+ elif self.skip_clear_for == -3: # Play until next checkpoint:
2288
+ if self.server_checkpoints["matched"] >= 0:
2289
+ self.step_event.clear()
2290
+ else:
2291
+ self.skip_clear_for -= 1
2292
+
2293
+ self.synch_cycle += 1
2294
+
2295
+ # Stop condition on the number of cycles
2296
+ if self.synch_cycles is not None and self.synch_cycle == self.synch_cycles:
2297
+ break
2298
+ except KeyboardInterrupt:
2299
+ print("\nDetected Ctrl+C! Exiting gracefully...")