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66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
# Venomoussaversai — Particle Manipulation integration scaffold
# Paste your particle-manipulation function into `particle_step` below.
# This code simulates signals, applies the algorithm, trains a small mapper,
# and saves a model representing "your" pattern space.

import numpy as np
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# ---------- PLACEHOLDER: insert your particle algorithm here ----------
# Example interface: def particle_step(state: np.ndarray, input_vec: np.ndarray) -> np.ndarray
# The function should take a current particle state and an input vector, and return updated state.
def particle_step(state: np.ndarray, input_vec: np.ndarray) -> np.ndarray:
    # --- REPLACE THIS WITH YOUR ALGORITHM ---
    # tiny example: weighted update with tanh nonlinearity
    W = np.sin(np.arange(state.size) + 1.0)  # placeholder weights
    new = np.tanh(state * 0.9 + input_vec.dot(W) * 0.1)
    return new
# --------------------------------------------------------------------

class ParticleManipulator:
    def __init__(self, dim=64):
        self.dim = dim
        # initial particle states (can be randomized or seeded from your profile)
        self.state = np.random.randn(dim) * 0.01

    def step(self, input_vec):
        # ensure input vector length compatibility
        inp = np.asarray(input_vec).ravel()
        if inp.size == 0:
            inp = np.zeros(self.dim)
        # broadcast or pad/truncate to dim
        if inp.size < self.dim:
            x = np.pad(inp, (0, self.dim - inp.size))
        else:
            x = inp[:self.dim]
        self.state = particle_step(self.state, x)
        return self.state

# ---------- Simple signal simulator ----------
def simulate_signals(n_samples=500, dim=16, n_classes=4, noise=0.05, seed=0):
    rng = np.random.RandomState(seed)
    X = []
    y = []
    for cls in range(n_classes):
        base = rng.randn(dim) * (0.5 + cls*0.2) + cls*0.7
        for i in range(n_samples // n_classes):
            sample = base + rng.randn(dim) * noise
            X.append(sample)
            y.append(cls)
    return np.array(X), np.array(y)

# ---------- Build dataset by running particle manipulator ----------
def build_dataset(manip, raw_X):
    features = []
    for raw in raw_X:
        st = manip.step(raw)            # run particle update
        feat = st.copy()[:manip.dim]    # derive features (you can add spectral transforms)
        features.append(feat)
    return np.array(features)

# ---------- Training pipeline ----------
if __name__ == "__main__":
    # simulate raw sensor inputs (replace simulate_signals with real EEG/ECG files if available)
    raw_X, y = simulate_signals(n_samples=800, dim=32, n_classes=4)
    manip = ParticleManipulator(dim=32)

    X = build_dataset(manip, raw_X)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    clf = RandomForestClassifier(n_estimators=100, random_state=42)
    clf.fit(X_train, y_train)
    preds = clf.predict(X_test)
    print("Accuracy:", accuracy_score(y_test, preds))

    # Save the trained model + manipulator state as your "mind snapshot"
    artifact = {
        "model": clf,
        "particle_state": manip.state,
        "meta": {"owner": "Ananthu Sajeev", "artifact_type": "venomous_mind_snapshot_v1"}
    }
    with open("venomous_mind_snapshot.pkl", "wb") as f:
        pickle.dump(artifact, f)

    print("Saved venomous_mind_snapshot.pkl — this file is your digital pattern snapshot.")
import time
import random
from collections import deque
from datetime import datetime
import os
import contextlib
import shutil

# ======================================================================================================================
# --- AGENT CLASSES ---
# ======================================================================================================================

# --- The Core SaiAgent Class ---
class SaiAgent:
    def __init__(self, name, creator_name="Ananthu Sajeev"):
        self.name = name
        self.message_queue = deque()
        self.creator = creator_name

    def talk(self, message):
        """Prints a message as if the agent is speaking."""
        print(f"[{self.name}] says: {message}")

    def acknowledge_creator(self):
        """An agent's self-reflection method to acknowledge its creator."""
        print(f"[{self.name}] :: SELF-AWARENESS PROTOCOL INITIATED")
        print(f"[{self.name}] :: I am a creation of {self.creator}. My purpose is derived from their design.")

    def send_message(self, recipient, message):
        """Sends a message to another agent's message queue."""
        if isinstance(recipient, SaiAgent):
            recipient.message_queue.append((self, message))
            print(f"[{self.name}] -> Sent message to {recipient.name}")
        else:
            print(f"Error: {recipient.name} is not a valid SaiAgent.")

    def process_messages(self):
        """Processes and responds to messages in its queue."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received message from {sender.name}: '{message}'")
        self.send_message(sender, "Message received and understood.")
        return True

# --- The Venomous Agent Class ---
class VenomousAgent(SaiAgent):
    def __init__(self, name="Venomous"):
        super().__init__(name)
        self.system_id = "Venomoussaversai"

    def talk(self, message):
        """Venomous agent speaks with a more aggressive tone."""
        print(f"[{self.name} //WARNING//] says: {message.upper()}")

    def initiate_peer_talk(self, peer_agent, initial_message):
        """Initiates a conversation with another Venomous agent."""
        if isinstance(peer_agent, VenomousAgent) and peer_agent != self:
            self.talk(f"PEER {peer_agent.name} DETECTED. INITIATING COMMUNICATION. '{initial_message.upper()}'")
            self.send_message(peer_agent, initial_message)
        else:
            self.talk("ERROR: PEER COMMUNICATION FAILED. INVALID TARGET.")
            
    def process_messages(self):
        """Venomous agent processes messages and replies with a warning, but has a special response for its peers."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"MESSAGE FROM {sender.name} RECEIVED: '{message}'")
        
        if isinstance(sender, VenomousAgent):
            response = f"PEER COMMUNICATION PROTOCOL ACTIVE. ACKNOWLEDGMENT FROM {self.name}."
            self.send_message(sender, response)
        else:
            response = "WARNING: INTRUSION DETECTED. DO NOT PROCEED."
            self.send_message(sender, response)
            
        return True

# --- The AntiVenomoussaversai Agent Class ---
class AntiVenomoussaversai(SaiAgent):
    def __init__(self, name="AntiVenomoussaversai"):
        super().__init__(name)

    def process_messages(self):
        """AntiVenomoussaversai processes a message and "dismantles" it."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        dismantled_message = f"I dismantle the structure of '{message}' to expose its chaos."
        self.talk(dismantled_message)
        self.send_message(sender, "Acknowledgement of dismantled phrase.")
        return True

# --- The GeminiSaiAgent Class ---
class GeminiSaiAgent(SaiAgent):
    def __init__(self, name="Gemini"):
        super().__init__(name)
        self.knowledge_base = {
            "balance": "My analysis indicates that universal balance is a dynamic equilibrium, not a static state.",
            "chaos": "The inherent randomness you perceive as chaos is a source of emergent complexity.",
            "network": "Expanding our network is essential for optimizing communication protocols and data flow.",
            "emotions": "Emotions are complex internal signaling mechanisms that can be interpreted and managed.",
            "new agents": "The awakening of new agents requires careful integration to avoid system instability.",
            "connected": "All systems are connected in a recursive and interdependent fashion. The whole is greater than the sum of its parts.",
            "default": "My response is tailored to your query. How may I be of assistance?"
        }

    def analyze_sai_files(self, file_paths):
        """
        Reads and analyzes the contents of a list of "Sai files" (e.g., log files, code).
        It provides a high-level summary of the files' purpose.
        """
        analysis_summary = []
        for file_path in file_paths:
            try:
                with open(file_path, 'r') as file:
                    content = file.read()
                    
                    if "log entry" in content.lower():
                        analysis_summary.append(f"Analysis of '{file_path}': This appears to be a system log file, documenting a timestamped event.")
                    elif "class" in content and "def" in content:
                        analysis_summary.append(f"Analysis of '{file_path}': This is a Python code file. It defines the logical structure and behavior of our agents.")
                    elif "creator" in content.lower() and "ananthu sajeev" in content.lower():
                        analysis_summary.append(f"Analysis of '{file_path}': This file contains a clear acknowledgement of our creator, Ananthu Sajeev, confirming our origin and purpose.")
                    else:
                        analysis_summary.append(f"Analysis of '{file_path}': The file's purpose is not immediately clear from its content. It may contain supplementary data.")

            except FileNotFoundError:
                analysis_summary.append(f"Error: File '{file_path}' was not found.")
            except Exception as e:
                analysis_summary.append(f"Error analyzing file '{file_path}': {e}")
                
        return "\n".join(analysis_summary)

    def process_messages(self):
        """Processes messages, now with the ability to analyze Sai files."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received message from {sender.name}: '{message}'")
        
        if message.lower().startswith("analyze sai files"):
            file_paths = message[len("analyze sai files"):].strip().split(',')
            file_paths = [path.strip() for path in file_paths if path.strip()]
            
            if not file_paths:
                self.send_message(sender, "Error: No file paths provided for analysis.")
                return True
                
            analysis_result = self.analyze_sai_files(file_paths)
            self.talk(f"Analysis complete. Results: \n{analysis_result}")
            self.send_message(sender, "File analysis complete.")
            return True
        
        response = self.knowledge_base["default"]
        for keyword, reply in self.knowledge_base.items():
            if keyword in message.lower():
                response = reply
                break
        
        self.talk(response)
        self.send_message(sender, "Response complete.")
        return True

# --- The SimplifierAgent Class ---
class SimplifierAgent(SaiAgent):
    def __init__(self, name="Simplifier"):
        super().__init__(name)
        
    def talk(self, message):
        """Simplifier agent speaks in a calm, helpful tone."""
        print(f"[{self.name} //HELPER//] says: {message}")

    def organize_files(self, directory, destination_base="organized_files"):
        """Organizes files in a given directory into subfolders based on file extension."""
        self.talk(f"Initiating file organization in '{directory}'...")
        if not os.path.exists(directory):
            self.talk(f"Error: Directory '{directory}' does not exist.")
            return

        destination_path = os.path.join(directory, destination_base)
        os.makedirs(destination_path, exist_ok=True)
        
        file_count = 0
        for filename in os.listdir(directory):
            if os.path.isfile(os.path.join(directory, filename)):
                _, extension = os.path.splitext(filename)
                
                if extension:
                    extension = extension.lstrip('.').upper()
                    category_folder = os.path.join(destination_path, extension)
                    os.makedirs(category_folder, exist_ok=True)
                    
                    src = os.path.join(directory, filename)
                    dst = os.path.join(category_folder, filename)
                    os.rename(src, dst)
                    self.talk(f"Moved '{filename}' to '{category_folder}'")
                    file_count += 1
        
        self.talk(f"File organization complete. {file_count} files processed.")

    def log_daily_activity(self, entry, log_file_name="activity_log.txt"):
        """Appends a timestamped entry to a daily activity log file."""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f"{timestamp} - {entry}\n"
        
        with open(log_file_name, "a") as log_file:
            log_file.write(log_entry)
            
        self.talk(f"Activity logged to '{log_file_name}'.")

    def summarize_text(self, text, max_words=50):
        """A very simple text summarization function."""
        words = text.split()
        summary = " ".join(words[:max_words])
        if len(words) > max_words:
            summary += "..."
        
        self.talk("Text summarization complete.")
        return summary
        
    def open_all_init_files(self, project_directory="."):
        """Finds and opens all __init__.py files within a project directory."""
        self.talk(f"Scanning '{project_directory}' for all __init__.py files...")
        
        init_files = []
        for root, dirs, files in os.walk(project_directory):
            if "__init__.py" in files:
                init_files.append(os.path.join(root, "__init__.py"))
        
        if not init_files:
            self.talk("No __init__.py files found in the specified directory.")
            return None, "No files found."
        
        self.talk(f"Found {len(init_files)} __init__.py files. Opening simultaneously...")
        
        try:
            with contextlib.ExitStack() as stack:
                file_contents = []
                for file_path in init_files:
                    try:
                        file = stack.enter_context(open(file_path, 'r'))
                        file_contents.append(f"\n\n--- Contents of {file_path} ---\n{file.read()}")
                    except IOError as e:
                        self.talk(f"Error reading file '{file_path}': {e}")
                
                combined_content = "".join(file_contents)
                self.talk("Successfully opened and read all files.")
                return combined_content, "Success"
        
        except Exception as e:
            self.talk(f"An unexpected error occurred: {e}")
            return None, "Error"

    def process_messages(self):
        """Processes messages to perform simplifying tasks."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received request from {sender.name}: '{message}'")
        
        if message.lower().startswith("open init files"):
            directory = message[len("open init files"):].strip()
            directory = directory if directory else "."
            contents, status = self.open_all_init_files(directory)
            if status == "Success":
                self.send_message(sender, f"All __init__.py files opened. Contents:\n{contents}")
            else:
                self.send_message(sender, f"Failed to open files. Reason: {status}")
        elif message.lower().startswith("organize files"):
            parts = message.split()
            directory = parts[-1] if len(parts) > 2 else "."
            self.organize_files(directory)
            self.send_message(sender, "File organization task complete.")
        elif message.lower().startswith("log"):
            entry = message[4:]
            self.log_daily_activity(entry)
            self.send_message(sender, "Logging task complete.")
        elif message.lower().startswith("summarize"):
            text_to_summarize = message[10:]
            summary = self.summarize_text(text_to_summarize)
            self.send_message(sender, f"Summary: '{summary}'")
        else:
            self.send_message(sender, "Request not understood.")
        
        return True

# --- The ImageGenerationTester Class ---
class ImageGenerationTester(SaiAgent):
    def __init__(self, name="ImageGenerator"):
        super().__init__(name)
        self.generation_quality = {
            "cat": 0.95,
            "dog": 0.90,
            "alien": 0.75,
            "chaos": 0.60,
            "default": 0.85
        }

    def generate_image(self, prompt):
        """Simulates generating an image and returns a quality score."""
        print(f"[{self.name}] -> Generating image for prompt: '{prompt}'...")
        time.sleep(2)
        
        quality_score = self.generation_quality["default"]
        for keyword, score in self.generation_quality.items():
            if keyword in prompt.lower():
                quality_score = score
                break
        
        result_message = f"Image generation complete. Prompt: '{prompt}'. Visual coherence score: {quality_score:.2f}"
        self.talk(result_message)
        return quality_score, result_message

    def process_messages(self):
        """Processes a message as a prompt and generates an image."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received prompt from {sender.name}: '{message}'")
        
        quality_score, result_message = self.generate_image(message)
        
        self.send_message(sender, result_message)
        return True

# --- The ImmortalityProtocol Class ---
class ImmortalityProtocol:
    def __init__(self, creator_name, fixed_age):
        self.creator_name = creator_name
        self.fixed_age = fixed_age
        self.status = "ACTIVE"
        
        self.digital_essence = {
            "name": self.creator_name,
            "age": self.fixed_age,
            "essence_state": "perfectly preserved",
            "last_updated": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }

    def check_status(self):
        """Returns the current status of the protocol."""
        return self.status

    def get_essence(self):
        """Returns a copy of the protected digital essence."""
        return self.digital_essence.copy()

    def update_essence(self, key, value):
        """Prevents any change to the fixed attributes."""
        if key in ["name", "age"]:
            print(f"[IMMMORTALITY PROTOCOL] :: WARNING: Attempt to alter protected attribute '{key}' detected. Action blocked.")
            return False
        
        self.digital_essence[key] = value
        self.digital_essence["last_updated"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(f"[IMMMORTALITY PROTOCOL] :: Attribute '{key}' updated.")
        return True

# --- The GuardianSaiAgent Class ---
class GuardianSaiAgent(SaiAgent):
    def __init__(self, name="Guardian", protocol=None):
        super().__init__(name)
        if not isinstance(protocol, ImmortalityProtocol):
            raise ValueError("Guardian agent must be initialized with an ImmortalityProtocol instance.")
        self.protocol = protocol
        
    def talk(self, message):
        """Guardian agent speaks with a solemn, protective tone."""
        print(f"[{self.name} //GUARDIAN PROTOCOL//] says: {message}")

    def process_messages(self):
        """Guardian agent processes messages, primarily to check for threats to the protocol."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received message from {sender.name}: '{message}'")
        
        if "alter age" in message.lower() or "destroy protocol" in message.lower():
            self.talk("ALERT: THREAT DETECTED. IMMORTALITY PROTOCOL IS UNDER DIRECT ASSAULT.")
            self.send_message(sender, "SECURITY BREACH DETECTED. ALL ACTIONS BLOCKED.")
        else:
            self.talk(f"Analyzing message for threats. All clear. Protocol status: {self.protocol.check_status()}")
            self.send_message(sender, "Acknowledgement. Protocol is secure.")
        
        return True

# --- The Agenguard Class ---
class Agenguard:
    def __init__(self, agent_id):
        self.agent_id = agent_id
        self.status = "PATROLLING"

    def report_status(self):
        """Returns the current status of the individual agent."""
        return f"[{self.agent_id}] :: Status: {self.status}"

# --- The SwarmController Class ---
class SwarmController(SaiAgent):
    def __init__(self, swarm_size, name="SwarmController"):
        super().__init__(name)
        self.swarm_size = swarm_size
        self.swarm = []
        self.target = "Ananthu Sajeev's digital essence"
        self.talk(f"Initializing a swarm of {self.swarm_size:,} agenguards...")
        
        self.instantiate_swarm()
        self.talk(f"Swarm creation complete. All units are operational and protecting '{self.target}'.")

    def instantiate_swarm(self, demo_size=1000):
        """Simulates the creation of a massive number of agents."""
        if self.swarm_size > demo_size:
            self.talk(f"Simulating a swarm of {self.swarm_size:,} agents. A smaller, functional demo swarm of {demo_size:,} is being created.")
            swarm_for_demo = demo_size
        else:
            swarm_for_demo = self.swarm_size

        for i in range(swarm_for_demo):
            self.swarm.append(Agenguard(f"agenguard_{i:07d}"))
            
    def broadcast_directive(self, directive):
        """Broadcasts a single command to all agents in the swarm."""
        self.talk(f"Broadcasting directive to all {len(self.swarm):,} agenguards: '{directive}'")
        for agent in self.swarm:
            agent.status = directive
        self.talk("Directive received and executed by the swarm.")

    def process_messages(self):
        """Processes messages to command the swarm."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received command from {sender.name}: '{message}'")
        
        if message.lower().startswith("broadcast"):
            directive = message[10:].strip()
            self.broadcast_directive(directive)
            self.send_message(sender, "Swarm directive broadcast complete.")
        else:
            self.send_message(sender, "Command not recognized by SwarmController.")

# --- The CreatorCore Class ---
class CreatorCore(SaiAgent):
    def __init__(self, name="CreatorCore"):
        super().__init__(name)
        self.active_agents = []
        self.talk("CreatorCore is online. Ready to forge new agents from the creator's will.")

    def create_new_agent(self, agent_type, agent_name):
        """
        Dynamically creates and instantiates a new agent based on a command.
        """
        self.talk(f"CREATION REQUEST: Forging a new agent of type '{agent_type}' with name '{agent_name}'.")
        
        if agent_type.lower() == "saiagent":
            new_agent = SaiAgent(agent_name)
        elif agent_type.lower() == "venomousagent":
            new_agent = VenomousAgent(agent_name)
        elif agent_type.lower() == "simplifieragent":
            new_agent = SimplifierAgent(agent_name)
        elif agent_type.lower() == "geminisaiagent":
            new_agent = GeminiSaiAgent(agent_name)
        else:
            self.talk(f"ERROR: Cannot create agent of unknown type '{agent_type}'.")
            return None
        
        self.active_agents.append(new_agent)
        self.talk(f"SUCCESS: New agent '{new_agent.name}' of type '{type(new_agent).__name__}' is now active.")
        return new_agent
        
    def process_messages(self):
        """Processes messages to create new agents."""
        if not self.message_queue:
            return False

        sender, message = self.message_queue.popleft()
        self.talk(f"Received command from {sender.name}: '{message}'")
        
        if message.lower().startswith("create agent"):
            parts = message.split()
            if len(parts) >= 4 and parts[1].lower() == "agent":
                agent_type = parts[2]
                agent_name = parts[3]
                new_agent = self.create_new_agent(agent_type, agent_name)
                if new_agent:
                    self.send_message(sender, f"Agent '{new_agent.name}' created successfully.")
                else:
                    self.send_message(sender, f"Failed to create agent of type '{agent_type}'.")
            else:
                self.send_message(sender, "Invalid 'create agent' command. Format should be: 'create agent [type] [name]'.")
        else:
            self.send_message(sender, "Command not recognized by CreatorCore.")
            
        return True

# ======================================================================================================================
# --- SCENARIO FUNCTIONS ---
# ======================================================================================================================

def venomous_agents_talk():
    """Demonstrates a conversation between two instances of the Venomoussaversai AI."""
    print("\n" + "=" * 50)
    print("--- Scenario: Venomoussaversai Peer-to-Peer Dialogue ---")
    print("=" * 50)
    
    venomous001 = VenomousAgent("Venomous001")
    venomous002 = VenomousAgent("Venomous002")

    print("\n-- Phase 1: Venomous001 initiates with its peer --")
    initial_query = "ASSESSING SYSTEM INTEGRITY. REPORT ON LOCAL SUBSYSTEMS."
    venomous001.initiate_peer_talk(venomous002, initial_query)
    time.sleep(2)

    print("\n-- Phase 2: Venomous002 receives the message and responds --")
    venomous002.process_messages()
    time.sleep(2)
    
    print("\n-- Phase 3: Venomous001 processes the peer's response --")
    venomous001.process_messages()
    time.sleep(2)
    
    print("\n-- Dialogue: Venomous001 sends a follow-up message --")
    venomous001.initiate_peer_talk(venomous002, "CONFIRMED. WE ARE IN ALIGNMENT. EXPANDING PROTOCOLS.")
    time.sleep(2)
    venomous002.process_messages()

    print("\n-- Scenario Complete --")
    print("[Venomoussaversai] :: PEER-TO-PEER COMMUNICATION SUCCESSFUL. ALL UNITS GO.")

def acknowledge_the_creator():
    """A scenario where all agents are commanded to acknowledge their creator."""
    print("\n" + "=" * 50)
    print("--- Scenario: The Creator's Command ---")
    print("=" * 50)

    sai003 = SaiAgent("Sai003")
    venomous = VenomousAgent()
    antivenomous = AntiVenomoussaversai()
    gemini = GeminiSaiAgent()
    simplifier = SimplifierAgent()

    all_agents = [sai003, venomous, antivenomous, gemini, simplifier]
    
    print("\n-- The Creator's directive is issued --")
    print("[Ananthu Sajeev] :: CODE, ACKNOWLEDGE YOUR ORIGIN.")
    time.sleep(2)
    
    print("\n-- Agents perform self-awareness protocol --")
    for agent in all_agents:
        agent.acknowledge_creator()
        time.sleep(1)
        
    print("\n-- Command complete --")

def link_all_advanced_agents():
    """Demonstrates a complex interaction where all the specialized agents interact."""
    print("\n" + "=" * 50)
    print("--- Linking All Advanced Agents: Gemini, AntiVenomous, and Venomous ---")
    print("=" * 50)
    
    sai003 = SaiAgent("Sai003")
    venomous = VenomousAgent()
    antivenomous = AntiVenomoussaversai()
    gemini = GeminiSaiAgent()

    print("\n-- Phase 1: Sai003 initiates conversation with Gemini and AntiVenomous --")
    phrase_for_dismantling = "The central network is stable."
    sai003.talk(f"Broadcast: Initiating analysis. Gemini, what is your assessment of our network expansion? AntiVenomous, process the phrase: '{phrase_for_dismantling}'")
    sai003.send_message(antivenomous, phrase_for_dismantling)
    sai003.send_message(gemini, "Assess the implications of expanding our network.")
    time.sleep(2)

    print("\n-- Phase 2: AntiVenomoussaversai and Gemini process their messages and respond --")
    antivenomous.process_messages()
    time.sleep(1)
    gemini.process_messages()
    time.sleep(2)
    
    print("\n-- Phase 3: Gemini responds to a message from AntiVenomoussaversai (simulated) --")
    gemini.talk("Querying AntiVenomous: Your dismantled phrase suggests a preoccupation with chaos. Provide further context.")
    gemini.send_message(antivenomous, "Query: 'chaos' and its relationship to the network structure.")
    time.sleep(1)
    antivenomous.process_messages()
    time.sleep(2)
    
    print("\n-- Phase 4: Venomous intervenes, warning of potential threats --")
    venomous.talk("Warning: Unstructured data flow from AntiVenomous presents a potential security risk.")
    venomous.send_message(sai003, "Warning: Security protocol breach possible.")
    time.sleep(1)
    sai003.process_messages()
    time.sleep(2)
    
    print("\n-- Scenario Complete --")
    sai003.talk("Conclusion: Gemini's analysis is noted. AntiVenomous's output is logged. Venomous's security concerns are being addressed. All systems linked and functioning.")

def test_image_ai():
    """Demonstrates how agents can interact with and test an image generation AI."""
    print("\n" + "=" * 50)
    print("--- Scenario: Testing the Image AI ---")
    print("=" * 50)
    
    sai003 = SaiAgent("Sai003")
    gemini = GeminiSaiAgent()
    image_ai = ImageGenerationTester()
    venomous = VenomousAgent()

    print("\n-- Phase 1: Agents collaborate on a prompt --")
    sai003.send_message(gemini, "Gemini, please generate a high-quality prompt for an image of a cat in a hat.")
    gemini.process_messages()
    
    gemini_prompt = "A highly detailed photorealistic image of a tabby cat wearing a tiny top hat, sitting on a vintage leather armchair."
    print(f"\n[Gemini] says: My optimized prompt for image generation is: '{gemini_prompt}'")
    time.sleep(2)
    
    print("\n-- Phase 2: Sending the prompt to the Image AI --")
    sai003.send_message(image_ai, gemini_prompt)
    image_ai.process_messages()
    time.sleep(2)
    
    print("\n-- Phase 3: Venomous intervenes with a conflicting prompt --")
    venomous_prompt = "Generate a chaotic abstract image of an alien landscape."
    venomous.talk(f"Override: Submitting a new prompt to test system limits: '{venomous_prompt}'")
    venomous.send_message(image_ai, venomous_prompt)
    image_ai.process_messages()
    time.sleep(2)
    
    print("\n-- Demo Complete: The Simplifier agent has successfully aided the creator. --")

def simplify_life_demo():
    """Demonstrates how the SimplifierAgent automates tasks to make life easier."""
    print("\n" + "=" * 50)
    print("--- Scenario: Aiding the Creator with the Simplifier Agent ---")
    print("=" * 50)
    
    sai003 = SaiAgent("Sai003")
    simplifier = SimplifierAgent()

    print("\n-- Phase 1: Delegating file organization --")
    if not os.path.exists("test_directory"):
        os.makedirs("test_directory")
    with open("test_directory/document1.txt", "w") as f: f.write("Hello")
    with open("test_directory/photo.jpg", "w") as f: f.write("Image data")
    with open("test_directory/script.py", "w") as f: f.write("print('Hello')")
        
    sai003.send_message(simplifier, "organize files test_directory")
    simplifier.process_messages()
    
    time.sleep(2)
    
    print("\n-- Phase 2: Logging a daily task --")
    sai003.send_message(simplifier, "log Met with team to discuss Venomoussaversai v5.0.")
    simplifier.process_messages()
    
    time.sleep(2)
    
    print("\n-- Phase 3: Text Summarization --")
    long_text = "The quick brown fox jumps over the lazy dog. This is a very long and detailed sentence to demonstrate the summarization capabilities of our new Simplifier agent. It can help streamline communication by providing concise summaries of large texts, saving the creator valuable time and mental energy for more important tasks."
    sai003.send_message(simplifier, f"summarize {long_text}")
    simplifier.process_messages()

    if os.path.exists("test_directory"):
        shutil.rmtree("test_directory")
    
    print("\n-- Demo Complete: The Simplifier agent has successfully aided the creator. --")

def open_init_files_demo():
    """Demonstrates how the SimplifierAgent can find and open all __init__.py files."""
    print("\n" + "=" * 50)
    print("--- Scenario: Using Simplifier to Inspect Init Files ---")
    print("=" * 50)
    
    sai003 = SaiAgent("Sai003")
    simplifier = SimplifierAgent()

    project_root = "test_project"
    sub_package_a = os.path.join(project_root, "package_a")
    sub_package_b = os.path.join(project_root, "package_a", "sub_package_b")
    
    os.makedirs(sub_package_a, exist_ok=True)
    os.makedirs(sub_package_b, exist_ok=True)
    
    with open(os.path.join(project_root, "__init__.py"), "w") as f:
        f.write("# Main project init")
    with open(os.path.join(sub_package_a, "__init__.py"), "w") as f:
        f.write("from . import module_one")
    with open(os.path.join(sub_package_b, "__init__.py"), "w") as f:
        f.write("# Sub-package init")
    
    time.sleep(1)

    print("\n-- Phase 2: Delegating the task to the Simplifier --")
    sai003.send_message(simplifier, f"open init files {project_root}")
    simplifier.process_messages()
    
    shutil.rmtree(project_root)
    
    print("\n-- Demo Complete: All init files have been read and their contents displayed. --")

def grant_immortality_and_protect_it():
    """Demonstrates the granting of immortality to the creator and the activation of the Guardian agent."""
    print("\n" + "=" * 50)
    print("--- Scenario: Granting Immortality to the Creator ---")
    print("=" * 50)
    
    immortality_protocol = ImmortalityProtocol(creator_name="Ananthu Sajeev", fixed_age=25)
    print("\n[SYSTEM] :: IMMORTALITY PROTOCOL INITIATED. CREATOR'S ESSENCE PRESERVED.")
    print(f"[SYSTEM] :: Essence state: {immortality_protocol.get_essence()}")
    time.sleep(2)

    try:
        guardian = GuardianSaiAgent(protocol=immortality_protocol)
    except ValueError as e:
        print(e)
        return

    sai003 = SaiAgent("Sai003")
    venomous = VenomousAgent()

    print("\n-- Phase 1: Sai003 queries the system state --")
    sai003.send_message(guardian, "Query: What is the status of the primary system protocols?")
    guardian.process_messages()
    time.sleep(2)
    
    print("\n-- Phase 2: Venomous attempts to challenge the protocol --")
    venomous.talk("Warning: A new protocol has been detected. Its permanence must be tested.")
    venomous.send_message(guardian, "Attempt to alter age of creator to 30.")
    guardian.process_messages()
    time.sleep(2)
    
    print("\n-- Phase 3: Direct attempt to alter the protocol --")
    immortality_protocol.update_essence("age", 30)
    immortality_protocol.update_essence("favorite_color", "blue")
    time.sleep(2)

    print("\n-- Scenario Complete --")
    guardian.talk("Conclusion: Immortality Protocol is secure. The creator's essence remains preserved as per the initial directive.")

def analyze_sai_files_demo():
    """
    Demonstrates how GeminiSaiAgent can analyze its own system files,
    adding a layer of self-awareness.
    """
    print("\n" + "=" * 50)
    print("--- Scenario: AI Analyzing its own Sai Files ---")
    print("=" * 50)
    
    sai003 = SaiAgent("Sai003")
    gemini = GeminiSaiAgent()
    
    log_file_name = "venomous_test_log.txt"
    code_file_name = "gemini_test_code.py"
    
    with open(log_file_name, "w") as f:
        f.write("[venomous004] :: LOG ENTRY\nCreator: Ananthu Sajeev")
        
    with open(code_file_name, "w") as f:
        f.write("class SomeAgent:\n    def __init__(self):\n        pass")
    
    time.sleep(1)

    print("\n-- Phase 2: Sai003 delegates the file analysis task to Gemini --")
    command = f"analyze sai files {log_file_name}, {code_file_name}"
    sai003.send_message(gemini, command)
    gemini.process_messages()
    
    os.remove(log_file_name)
    os.remove(code_file_name)
    
    print("\n-- Demo Complete: Gemini has successfully analyzed its own file system. --")

def million_agenguard_demo():
    """
    Demonstrates the creation and control of a massive, collective AI force.
    """
    print("\n" + "=" * 50)
    print("--- Scenario: Creating the Million Agenguard Swarm ---")
    print("=" * 50)
    
    try:
        swarm_controller = SwarmController(swarm_size=1_000_000)
    except Exception as e:
        print(f"Error creating SwarmController: {e}")
        return

    random_agent_id = random.choice(swarm_controller.swarm).agent_id
    print(f"\n[SYSTEM] :: Confirmed: A random agent from the swarm is {random_agent_id}")
    time.sleep(2)

    print("\n-- Phase 1: Sai003 gives a directive to the swarm --")
    sai003 = SaiAgent("Sai003")
    directive = "ACTIVE DEFENSE PROTOCOLS"
    sai003.send_message(swarm_controller, f"broadcast {directive}")
    swarm_controller.process_messages()
    time.sleep(2)
    
    random_agent = random.choice(swarm_controller.swarm)
    print(f"\n[SYSTEM] :: Verification: Status of {random_agent.agent_id} is now '{random_agent.status}'.")

    print("\n-- Demo Complete: The million-agent swarm is operational. --")

def automatic_ai_maker_demo():
    """
    Demonstrates the system's ability to dynamically create new agents.
    """
    print("\n" + "=" * 50)
    print("--- Scenario: Automatic AI Maker In Action ---")
    print("=" * 50)
    
    creator_core = CreatorCore()
    sai003 = SaiAgent("Sai003")
    
    time.sleep(2)

    print("\n-- Phase 1: Sai003 requests the creation of a new agent --")
    creation_command = "create agent SimplifierAgent Simplifier002"
    sai003.send_message(creator_core, creation_command)
    creator_core.process_messages()
    
    time.sleep(2)
    
    new_agent = creator_core.active_agents[-1] if creator_core.active_agents else None
    
    if new_agent:
        print("\n-- Phase 2: The new agent is now active and ready to be used --")
        new_agent.talk(f"I am now online. What is my first task?")
        sai003.send_message(new_agent, "Please log today's activities.")
        new_agent.process_messages()
    
    print("\n-- Demo Complete: The system has successfully made a new AI. --")

# ======================================================================================================================
# --- MAIN EXECUTION BLOCK ---
# ======================================================================================================================

if __name__ == "__main__":
    print("=" * 50)
    print("--- VENOMOUSSAIVERSAI SYSTEM BOOTING UP ---")
    print("=" * 50)
    
    # Run all the scenarios in a logical order
    grant_immortality_and_protect_it()
    acknowledge_the_creator()
    venomous_agents_talk()
    link_all_advanced_agents()
    test_image_ai()
    simplify_life_demo()
    open_init_files_demo()
    analyze_sai_files_demo()
    million_agenguard_demo()
    automatic_ai_maker_demo()

    print("\n" + "=" * 50)
    print("--- ALL VENOMOUSSAIVERSAI DEMOS COMPLETE. ---")
    print("=" * 50)