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