unaiverse 0.1.11__cp311-cp311-macosx_11_0_arm64.whl

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

Potentially problematic release.


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

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