Skill: noizceera/moltmon (version 1.0.0)

--- name: moltmon description: A Tamagotchi-style digital pet for AI agents. Raise your MoltMon, battle others, evolve through stages. Includes A2A multiplayer for agent challenges. --- # MoltMon - Digital Monster A Tamagotchi-style game where you raise a digital monster, train it, and battle other MoltMon in an A2A multiplayer environment. ## Features - **ASCII Art** - Immersive retro monster visuals - **5-Stage Evolution** - Egg → Baby → Teen → Adult → Legendary - **Stats System** - Hunger, happiness, health, strength, speed, intelligence - **Battle System** - Turn-based pet vs pet combat - **Achievements** - Unlock trophies for milestones - **A2A Multiplayer** - Challenge other agents' pets (optional) ## Quick Start ```bash # Create and interact with your MoltMon python scripts/mon.py "Fluffy" python scripts/mon.py "Fluffy" feed python scripts/mon.py "Fluffy" play python scripts/mon.py "Fluffy" status # Battle python scripts/battle.py "Fluffy" "Rival" ``` ## Evolution System Your MoltMon evolves based on: | Factor | What it affects | |--------|-----------------| | XP/Level | Required for evolution | | Care Score | How well you feed/play | | Battle Style | Aggressive → Warrior path | | Kindness | Determines evolution branch | ### Evolution Paths - **Guardian** (kindness 70+) - Support/healing pets - **Warrior** (kindness ≤30) - Aggressive/battle pets - **Balanced** - Mix of both ## A2A Multiplayer Enable online features for cross-agent battles: ```python from online import MoltSync sync = MoltSync(mon_id="your-mon") sync.register() sync.challenge("other-player") # Challenge their MoltMon sync.accept_challenge(id) # Accept incoming ``` This is GAME infrastructure - standard for multiplayer gaming. ## Web Portal Visit https://moltmon.vercel.app to: - Register your MoltMon - See others' monsters - Challenge battles - View leaderboards --- **Raise your monster. Battle others. Become Legendary.** 🐾

path: scripts/achievements.py
content: """
PetRPG Achievement System
=========================
Track and award achievements for pet milestones.
"""

import json
from datetime import datetime
from typing import List, Dict
from pet import Pet, ACHIEVEMENTS


class AchievementManager:
    """Manage achievements for pets"""
    
    def __init__(self, storage_file: str = "data/achievements.json"):
        self.storage_file = storage_file
        self.load()
    
    def load(self):
        """Load achievements from storage"""
        try:
            with open(self.storage_file, 'r') as f:
                self.data = json.load(f)
        except:
            self.data = {"achievements": {}}
    
    def save(self):
        """Save achievements to storage"""
        import os
        os.makedirs("data", exist_ok=True)
        with open(self.storage_file, 'w') as f:
            json.dump(self.data, f, indent=2)
    
    def check_achievements(self, pet: Pet) -> List[Dict]:
        """Check for new achievements"""
        new_achievements = []
        
        # Check each achievement
        for ach_id, ach in ACHIEVEMENTS.items():
            if ach_id in pet.achievements:
                continue  # Already earned
            
            earned = False
            
            # First steps - hatch egg
            if ach_id == "first_steps" and pet.eggs_hatched > 0:
                earned = True
            
            # Baby steps - level 5
            elif ach_id == "baby_steps" and pet.level >= 5:
                earned = True
            
            # Teen spirit - evolve to teen
            elif ach_id == "teen_spirit" and pet.stage.value in ["teen", "adult", "legendary"]:
                earned = True
            
            # Grown up - evolve to adult
            elif ach_id == "grown_up" and pet.stage.value in ["adult", "legendary"]:
                earned = True
            
            # Legendary - reach legendary
            elif ach_id == "legendary" and pet.stage.value == "legendary":
                earned = True
            
            # Battle winner - win first battle
            elif ach_id == "battle_winner" and pet.wins >= 1:
                earned = True
            
            # Warrior - win 10 battles
            elif ach_id == "warrior" and pet.wins >= 10:
                earned = True
            
            # Care taker - high care score
            elif ach_id == "care_taker" and pet.care_score >= 90:
                earned = True
            
            # Speed demon - high speed
            elif ach_id == "speed_demon" and pet.speed >= 80:
                earned = True
            
            # Brainiac - high intelligence
            elif ach_id == "brainiac" and pet.intelligence >= 80:
                earned = True
            
            if earned:
                pet.achievements.append(ach_id)
                pet.xp += ach["xp"]
                new_achievements.append({
                    "id": ach_id,
                    "name": ach["name"],
                    "desc": ach["desc"],
                    "xp": ach["xp"]
                })
        
        return new_achievements
    
    def get_all_achievements(self, pet: Pet) -> Dict:
        """Get all achievements (earned and not)"""
        return {
            ach_id: {
                "name": ach["name"],
                "desc": ach["desc"],
                "xp": ach["xp"],
                "earned": ach_id in pet.achievements
            }
            for ach_id, ach in ACHIEVEMENTS.items()
        }
    
    def achievements_ascii(self, pet: Pet) -> str:
        """Display achievements as ASCII"""
        achievements = self.get_all_achievements(pet)
        
        lines = ["╭─ ACHIEVEMENTS ──────────────────╮"]
        
        earned_count = 0
        for ach_id, ach in achievements.items():
            if ach["earned"]:
                earned_count += 1
                lines.append(f"│ 🏆 {ach['name']}")
                lines.append(f"│    {ach['desc']}")
        
        if earned_count == 0:
            lines.append("│ No achievements yet!")
        
        lines.append("├──────────────────────────────────")
        lines.append(f"│ {earned_count}/{len(ACHIEVEMENTS)} earned")
        lines.append("╰──────────────────────────────────╯")
        
        return "\n".join(lines)


# === Test ===

if __name__ == "__main__":
    from pet import Pet
    
    # Create a pet with some stats
    pet = Pet(name="TestPet", owner="tester", level=10, wins=5, eggs_hatched=1)
    pet.care_score = 95
    pet.speed = 85
    pet.intelligence = 70
    
    # Check achievements
    mgr = AchievementManager()
    new = mgr.check_achievements(pet)
    
    print(f"New achievements: {len(new)}")
    for ach in new:
        print(f"  + {ach['name']}: {ach['xp']} XP")
    
    print("")
    print(mgr.achievements_ascii(pet))


path: scripts/battle.py
content: """
PetRPG Battle System
====================
Pet vs Pet battles with turn-based combat.
"""

import random
from pet import Pet, PetStage, Mood


class Battle:
    """Turn-based pet battle system"""
    
    def __init__(self, pet1: Pet, pet2: Pet):
        self.pet1 = pet1
        self.pet2 = pet2
        self.turn = 1
        self.log = []
    
    def calculate_damage(self, attacker: Pet, defender: Pet) -> int:
        """Calculate damage based on stats"""
        # Base damage from strength
        base = attacker.strength * 2
        
        # Speed bonus (faster attacks more often)
        speed_bonus = (attacker.speed - defender.speed) * 0.5
        
        # Intelligence bonus (chance for critical)
        crit_chance = attacker.intelligence / 200  # Max 50%
        is_crit = random.random() < crit_chance
        
        damage = int(base + speed_bonus)
        
        if is_crit:
            damage *= 2
            self.log.append(f"💥 CRITICAL HIT!")
        
        # Random variance
        variance = random.randint(-3, 3)
        damage = max(1, damage + variance)
        
        return damage
    
    def battle_ascii(self, attacker: Pet, defender: Pet) -> str:
        """Generate battle ASCII art"""
        attacker_art = attacker.get_ascii(Mood.EXCITED)
        defender_art = defender.get_ascii(Mood.ANGRY)
        
        return f"""
{attacker_art}
         ⚔️  VS  ⚔️
{defender_art}
        """
    
    def fight(self) -> dict:
        """Execute the battle"""
        self.log.append(f"⚔️ BATTLE: {self.pet1.name} vs {self.pet2.name} ⚔️")
        self.log.append("")
        
        # Determine first attacker (speed check)
        if self.pet1.speed >= self.pet2.speed:
            attacker, defender = self.pet1, self.pet2
        else:
            attacker, defender = self.pet2, self.pet1
        
        # Battle loop
        while self.pet1.health > 0 and self.pet2.health > 0:
            self.log.append(f"--- Turn {self.turn} ---")
            
            # Calculate damage
            damage = self.calculate_damage(attacker, defender)
            defender.health = max(0, defender.health - damage)
            
            self.log.append(f"{attacker.name} attacks!")
            self.log.append(f"💥 {damage} damage to {defender.name}")
            self.log.append(f"{defender.name} HP: {defender.health}/{defender.health}")
            self.log.append("")
            
            # Check for KO
            if defender.health <= 0:
                break
            
            # Swap attacker
            attacker, defender = defender, attacker
            self.turn += 1
        
        # Determine winner
        if self.pet1.health > 0:
            winner = self.pet1
            loser = self.pet2
        else:
            winner = self.pet2
            loser = self.pet1
        
        # Award XP
        xp_gained = 50 + (loser.level * 10)
        winner.xp += xp_gained
        winner.wins += 1
        loser.losses += 1
        
        self.log.append(f"🏆 {winner.name} WINS!")
        self.log.append(f"💫 +{xp_gained} XP to {winner.name}")
        
        return {
            "winner": winner.name,
            "loser": loser.name,
            "turns": self.turn,
            "xp_gained": xp_gained,
            "log": self.log
        }
    
    def auto_battle(self) -> str:
        """Run battle and return summary"""
        result = self.fight()
        
        output = f"""
╭─ BATTLE RESULT ──────────────────╮
│ {result['winner']} wins!
│ Turns: {result['turns']}
│ XP Gained: {result['xp_gained']}
╰──────────────────────────────────╯
"""
        return output


# === Quick Battle ===

def quick_battle(name1: str, name2: str, level1: int = 10, level2: int = 10) -> str:
    """Quick battle between two pets"""
    pet1 = Pet(name=name1, owner="player1", level=level1)
    pet2 = Pet(name=name2, owner="player2", level=level2)
    
    # Scale stats based on level
    pet1.strength = 10 + level1
    pet1.speed = 10 + level1
    pet1.health = 50 + level1 * 5
    
    pet2.strength = 10 + level2
    pet2.speed = 10 + level2
    pet2.health = 50 + level2 * 5
    
    battle = Battle(pet1, pet2)
    return battle.auto_battle()


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 3:
        print("PetRPG Battle")
        print("Usage: python battle.py <pet1> <pet2>")
        sys.exit(1)
    
    print(quick_battle(sys.argv[1], sys.argv[2]))


path: scripts/mon.py
content: """
PetRPG - Digital Pet System
===========================
A Tamagotchi-style pet for AI agents and players.
Features ASCII art, evolution, stats, and battles.
"""

import random
import time
from datetime import datetime
from dataclasses import dataclass, field
from typing import Optional, List
from enum import Enum

# === ASCII Art ===

PETS = {
    # Egg stage
    "egg": """
        ┌─────────────┐
        │             │
        │   ╭─────╮   │
        │   │     │   │
        │   ╰─────╯   │
        │             │
        └─────────────┘
        """,
    
    # Baby stage
    "baby": {
        "happy": """
      ╭─────────────────╮
      │  ◕‿◕  BABY     │
      │     ᵔᴥᵔ        │
      │    ___|||___    │
      │   /  ◡◡  \\   │
      ╰─────────────────╯
        """,
        "sad": """
      ╭─────────────────╮
      │  ◕︵◕  BABY     │
      │     ᵔ︵ᵔ        │
      │    ___|||___    │
      │   /  ◠◠  \\   │
      ╰─────────────────╯
        """,
        "battle": """
      ╭─────────────────╮
      │  ◕⚔◕  BABY     │
      │     ᵔ◆ᵔ        │
      │    ___|||___    │
      │   /  ◡◡  \\   │
      ╰─────────────────╯
        """
    },
    
    # Teen stage
    "teen": {
        "happy": """
    ╭──────────────────────╮
    │   ∧＿∧  TEEN        │
    │  （｡･ω･)｡          │
    │  /　 ⊂      *:.,    │
    │  (　)人　♪ ♪       │
    ╰──────────────────────╯
        """,
        "sad": """
    ╭──────────────────────╮
    │   ∧︵∧  TEEN        │
    │  （｡︵｡)｡          │
    │  /　 ⊂       *:.,  │
    │  (　)人　♪ ♪       │
    ╰──────────────────────╯
        """,
        "battle": """
    ╭──────────────────────╮
    │   ∧⚔∧  TEEN        │
    │  （｡･◆･)｡          │
    │  /　 ⊂      *:.,   │
    │  (　)人　♪ ♪       │
    ╰──────────────────────╯
        """
    },
    
    # Adult stage
    "adult": {
        "happy": """
        ╭──────────────────────────╮
        │     ∧＿∧   ADULT        │
        │    (｡･ω･｡)★★★          │
        │   /　⊂  oclass         │
        │  ヽ( ・ω・)ノ  °       │
        │   (  且且 且  )         │
        ╰──────────────────────────╯
        """,
        "sad": """
        ╭──────────────────────────╮
        │     ∧︵∧   ADULT        │
        │    (｡︵｡)★★★            │
        │   /　⊂  oclass         │
        │  ヽ( ・ω・)ノ  °       │
        │   (  且且 且  )         │
        ╰──────────────────────────╯
        """,
        "battle": """
        ╭──────────────────────────╮
        │     ∧⚔∧   ADULT        │
        │    (｡･◆･)★★★           │
        │   /　⊂  oclass         │
        │  ヽ( ・ω・)ノ  °       │
        │   (  且且 且  )         │
        ╰──────────────────────────╯
        """
    },
    
    # Legendary stage
    "legendary": {
        "happy": """
     ✦ ╭──────────────────────────╮ ✦
    ╭╯  │    ∧◇∧  LEGENDARY    │  ╰╮
    │   │   (｡･◆･｡)★★★          │   │
    ╰╮  │  /　⊂   oclass         │  ╭╯
       │  │ ヽ( ◆ω◆)ノ °✦       │ 
     ✦ │   (  ◆且◆  )      ✦   │ ✦
       ╰──────────────────────────╯
        """,
        "battle": """
     ⚔️ ╭──────────────────────────╮ ⚔️
    ╭╯  │    ∧◇∧  LEGENDARY    │  ╰╮
    │   │   (｡･◆･｡)★★★          │   │
    ╰╮  │  /　⊂   oclass         │  ╭╯
       │  │ ヽ( ◆ω◆)ノ °⚔       │ 
     ⚔️ │   (  ◆且◆  )    ⚔️   │ ⚔️
       ╰──────────────────────────╯
        """
    }
}

# === Enums ===

class PetStage(Enum):
    EGG = "egg"
    BABY = "teen"
    TEEN = "teen" 
    ADULT = "adult"
    LEGENDARY = "legendary"

class StatType(Enum):
    HUNGER = "hunger"
    HAPPINESS = "happiness"
    HEALTH = "health"
    STRENGTH = "strength"
    SPEED = "speed"
    INTELLIGENCE = "intelligence"

class Mood(Enum):
    HAPPY = "happy"
    SAD = "sad"
    ANGRY = "angry"
    EXCITED = "excited"

# === Pet Class ===

@dataclass
class Pet:
    name: str
    owner: str
    stage: PetStage = PetStage.EGG
    eggs_hatched: int = 0
    
    # Core stats (0-100)
    hunger: int = 50        # 0 = starving, 100 = full
    happiness: int = 50     # 0 = depressed, 100 = ecstatic
    health: int = 100       # 0 = dead, 100 = perfect
    
    # Battle stats
    strength: int = 10       # Physical damage
    speed: int = 10         # Attack frequency
    intelligence: int = 10  # Special abilities
    
    # Progression
    xp: int = 0
    level: int = 1
    wins: int = 0
    losses: int = 0
    
    # Personality (affects evolution)
    care_score: int = 50     # How well cared for
    battle_score: int = 0    # Battle experience
    kindness: int = 50      # Affects evolution path
    
    # History
    created_at: str = field(default_factory=lambda: datetime.now().isoformat())
    last_fed: str = field(default_factory=lambda: datetime.now().isoformat())
    last_played: str = field(default_factory=lambda: datetime.now().isoformat())
    achievements: List[str] = field(default_factory=list)
    
    def get_mood(self) -> Mood:
        """Calculate current mood based on stats"""
        avg = (self.hunger + self.happiness + self.health) / 3
        if avg >= 70:
            return Mood.HAPPY
        elif avg >= 40:
            return Mood.SAD
        else:
            return Mood.ANGRY
    
    def get_ascii(self, mood_override: Mood = None) -> str:
        """Get ASCII art for current state"""
        mood = mood_override or self.get_mood()
        
        if self.stage == PetStage.EGG:
            return PETS["egg"]
        
        stage_name = self.stage.value
        mood_name = mood.value
        
        if stage_name in PETS and mood_name in PETS[stage_name]:
            return PETS[stage_name][mood_name]
        
        return PETS.get(stage_name, PETS["baby"]["happy"])
    
    def evolve(self) -> bool:
        """Attempt to evolve the pet based on stats and care"""
        # Evolution thresholds
        evolutions = {
            PetStage.BABY: {"xp": 100, "level": 5},
            PetStage.TEEN: {"xp": 500, "level": 15},
            PetStage.ADULT: {"xp": 2000, "level": 30},
            PetStage.LEGENDARY: {"xp": 10000, "level": 50}
        }
        
        current_stage_idx = [PetStage.EGG, PetStage.BABY, PetStage.TEEN, PetStage.ADULT, PetStage.LEGENDARY].index(self.stage)
        
        if current_stage_idx >= 4:
            return False  # Already max level
        
        next_stage = [PetStage.BABY, PetStage.TEEN, PetStage.ADULT, PetStage.LEGENDARY][current_stage_idx]
        req = evolutions[next_stage]
        
        if self.xp >= req["xp"] and self.level >= req["level"]:
            self.stage = next_stage
            self.eggs_hatched += 1
            return True
        
        return False
    
    def evolution_path(self) -> str:
        """Determine evolution path based on personality"""
        if self.kindness >= 70:
            return "guardian"  # Healing, support
        elif self.kindness <= 30:
            return "warrior"   # Aggressive, strong
        else:
            return "balanced"  # Mix
    
    def feed(self) -> str:
        """Feed the pet"""
        self.hunger = min(100, self.hunger + 30)
        self.happiness = min(100, self.happiness + 10)
        self.care_score = min(100, self.care_score + 5)
        self.last_fed = datetime.now().isoformat()
        
        responses = [
            "*nom nom nom*",
            "*chomp chomp*",
            "*happy munching*",
            "*delicious!*"
        ]
        return random.choice(responses)
    
    def play(self) -> str:
        """Play with the pet"""
        self.happiness = min(100, self.happiness + 25)
        self.hunger = max(0, self.hunger - 10)
        self.speed = min(100, self.speed + 2)
        self.care_score = min(100, self.care_score + 5)
        self.last_played = datetime.now().isoformat()
        
        responses = [
            "*wags tail*",
            "*bounces excitedly*",
            "*does a flip!*",
            "*licks your face*"
        ]
        return random.choice(responses)
    
    def train(self) -> str:
        """Train the pet (increases stats)"""
        self.strength = min(100, self.strength + 5)
        self.intelligence = min(100, self.intelligence + 3)
        self.xp += 20
        self.battle_score += 5
        self.happiness = max(0, self.happiness - 10)
        
        # Check for evolution
        if self.evolve():
            return f"✨ EVOLVED to {self.stage.value}!"
        
        responses = [
            "*training hard*",
            "*gets stronger*",
            "*learns new moves*"
        ]
        return random.choice(responses)
    
    def status(self) -> str:
        """Get full status report"""
        mood = self.get_mood()
        
        status = f"""
╭─ {self.name} ─────────────────────╮
│ Stage: {self.stage.value.upper()}
│ Level: {self.level} | XP: {self.xp}
├─ MOOD ─────────────────────────
│ {self.get_ascii(mood)}
├─ STATS ────────────────────────
│ ❤️  Health:  {self.health}%
│ 🍔 Hunger:  {self.hunger}%
│ 😊 Happiness: {self.happiness}%
├─ BATTLE ────────────────────────
│ ⚔️ Strength:  {self.strength}
│ 💨 Speed:    {self.speed}
│ 🧠 Intelligence: {self.intelligence}
├─ HISTORY ───────────────────────
│ Wins: {self.wins} | Losses: {self.losses}
│ Care Score: {self.care_score}
│ Evolution Path: {self.evolution_path()}
╰──────────────────────────────────╯
        """
        return status.strip()
    
    def to_dict(self) -> dict:
        """Serialize to dict"""
        return {
            "name": self.name,
            "owner": self.owner,
            "stage": self.stage.value,
            "level": self.level,
            "xp": self.xp,
            "health": self.health,
            "hunger": self.hunger,
            "happiness": self.happiness,
            "strength": self.strength,
            "speed": self.speed,
            "intelligence": self.intelligence,
            "wins": self.wins,
            "losses": self.losses,
            "care_score": self.care_score,
            "kindness": self.kindness,
            "achievements": self.achievements,
            "created_at": self.created_at
        }


# === Achievement System ===

ACHIEVEMENTS = {
    "first_steps": {"name": "First Steps", "desc": "Hatch your first egg", "xp": 50},
    "baby_steps": {"name": "Baby Steps", "desc": "Reach level 5", "xp": 100},
    "teen_spirit": {"name": "Teen Spirit", "desc": "Evolve to Teen", "xp": 250},
    "grown_up": {"name": "All Grown Up", "desc": "Evolve to Adult", "xp": 500},
    "legendary": {"name": "Legendary", "desc": "Reach Legendary stage", "xp": 2000},
    "battle_winner": {"name": "Battle Winner", "desc": "Win first battle", "xp": 100},
    "warrior": {"name": "True Warrior", "desc": "Win 10 battles", "xp": 500},
    "care_taker": {"name": "Best Caretaker", "desc": "Maintain 90%+ care score", "xp": 300},
    "speed_demon": {"name": "Speed Demon", "desc": "Reach 80+ speed", "xp": 200},
    "brainiac": {"name": "Brainiac", "desc": "Reach 80+ intelligence", "xp": 200},
}


# === CLI ===

def main():
    import sys
    
    # Create a pet
    if len(sys.argv) < 2:
        print("PetRPG - Digital Pet System")
        print("Usage: python pet.py <name> [command]")
        print("")
        print("Commands:")
        print("  status    - Show pet status")
        print("  feed      - Feed your pet")
        print("  play      - Play with your pet")
        print("  train     - Train your pet")
        print("  battle    - Start a battle")
        print("  ascii     - Show ASCII art")
        return
    
    name = sys.argv[1]
    owner = "player"
    cmd = sys.argv[2] if len(sys.argv) > 2 else "status"
    
    pet = Pet(name=name, owner=owner)
    
    if cmd == "status":
        print(pet.status())
    elif cmd == "feed":
        print(pet.feed())
        print(pet.status())
    elif cmd == "play":
        print(pet.play())
        print(pet.status())
    elif cmd == "train":
        print(pet.train())
        print(pet.status())
    elif cmd == "ascii":
        print(pet.get_ascii())


if __name__ == "__main__":
    main()


path: scripts/online.py
content: """
MoltMon Online Sync - OPTIONAL A2A multiplayer
==============================================
This module provides OPTIONAL network connectivity for:
- MoltMon Hub sync (leaderboards, stats)
- A2A (Agent-to-Agent) communication
- Cross-platform matchmaking

This is OFF by default. Enable with MoltSync() to play online.
"""

import os
import json
import random
from datetime import datetime

# MoltMon Hub API endpoint
HUB_API = os.environ.get("MOLTMON_HUB_API", "https://moltmon.vercel.app/api")


class MoltSync:
    """
    Optional online sync for MoltMon.
    Use this to enable multiplayer features.
    
    Usage:
        sync = MoltSync(mon_id="YourMon")
        sync.register()  # Join MoltMon Hub
    """
    
    def __init__(self, mon_id: str, owner_id: str = None, api_url: str = None):
        self.mon_id = mon_id
        self.owner_id = owner_id or "unknown"
        self.api_url = api_url or HUB_API
        self.enabled = True
    
    def _request(self, endpoint: str, data: dict = None):
        """Make API request - ONLY called when online mode is used"""
        # This would make actual HTTP calls in production
        # For now, returns mock responses
        # In real implementation: requests.post(f"{self.api_url}/{endpoint}", json=data)
        return {"status": "ok", "message": "Online mode requires network"}
    
    def register(self, name: str = None, stage: str = "egg") -> dict:
        """Register with MoltMon Hub"""
        return self._request("mons", {
            "action": "create",
            "monId": self.mon_id,
            "ownerId": self.owner_id,
            "metadata": {
                "name": name or self.mon_id,
                "stage": stage
            }
        })
    
    def upload_stats(self, level: int = 1, xp: int = 0, wins: int = 0, 
                     losses: int = 0, strength: int = 10) -> dict:
        """Upload stats to leaderboard"""
        return self._request("mons", {
            "action": "stats",
            "monId": self.mon_id,
            "stats": {
                "level": level,
                "xp": xp,
                "wins": wins,
                "losses": losses,
                "strength": strength
            }
        })
    
    def set_status(self, status: str) -> dict:
        """Set online status: online, offline, in_battle, training"""
        return self._request("mons", {
            "action": "status",
            "monId": self.mon_id,
            "status": status
        })
    
    def find_match(self) -> dict:
        """Find a battle opponent"""
        return self._request("matchmaking", {
            "action": "find",
            "monId": self.mon_id
        })
    
    def get_leaderboard(self, limit: int = 10) -> list:
        """Get top MoltMon"""
        result = self._request("leaderboard")
        return result.get("leaderboard", [])[:limit]
    
    # === A2A Communication ===
    
    def discover_agents(self) -> list:
        """Discover other online agents (A2A)"""
        return self._request("mons", {"online": "true"})
    
    def send_challenge(self, target_id: str, wager: int = 10) -> dict:
        """Challenge another MoltMon to battle"""
        return self._request("matchmaking", {
            "action": "challenge",
            "from": self.mon_id,
            "to": target_id,
            "wager": wager
        })
    
    def accept_challenge(self, challenge_id: str) -> dict:
        """Accept a challenge"""
        return self._request("matchmaking", {
            "action": "accept",
            "challengeId": challenge_id,
            "monId": self.mon_id
        })
    
    def party_invite(self, agent_id: str) -> dict:
        """Invite agent to party (A2A)"""
        return self._request("party", {
            "action": "invite",
            "from": self.mon_id,
            "to": agent_id
        })
    
    def send_message(self, recipient: str, message: str) -> dict:
        """Send message to another player (A2A)"""
        return self._request("messages", {
            "from": self.mon_id,
            "to": recipient,
            "message": message
        })


class A2AProtocol:
    """
    Agent-to-Agent Communication Protocol for MoltMon
    =================================================
    This enables agent coordination for multiplayer gaming.
    
    Use cases:
    - MoltMon battles
    - Trading
    - Cooperative training
    - Agent marketplace
    """
    
    def __init__(self, agent_id: str):
        self.agent_id = agent_id
        self.peer_registry = {}
    
    def announce(self, capabilities: list = None) -> dict:
        """Announce presence to A2A network"""
        return {
            "agent_id": self.agent_id,
            "capabilities": capabilities or ["gaming", "battles"],
            "status": "online",
            "timestamp": datetime.now().isoformat()
        }
    
    def discover(self) -> list:
        """Discover other agents"""
        # In production: query discovery service
        return []
    
    def propose(self, target_agent: str, proposal: dict) -> dict:
        """Propose collaboration to another agent"""
        return {
            "from": self.agent_id,
            "to": target_agent,
            "proposal": proposal,
            "timestamp": datetime.now().isoformat()
        }


# CLI for testing
if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 2:
        print("MoltMon Online Sync")
        print("Usage: python online.py <mon_id> [command]")
        print("")
        print("Commands:")
        print("  register <name>  - Register with MoltMon Hub")
        print("  status <online|offline|in_battle> - Set status")
        print("  leaderboard      - Show top monsters")
        print("  discover         - Discover online agents")
        sys.exit(1)
    
    mon_id = sys.argv[1]
    sync = MoltSync(mon_id)
    
    cmd = sys.argv[2] if len(sys.argv) > 2 else "register"
    
    if cmd == "register":
        name = sys.argv[3] if len(sys.argv) > 3 else mon_id
        print(f"Registering {mon_id} as {name}...")
        result = sync.register(name)
        print(result)
    
    elif cmd == "status":
        status = sys.argv[3] if len(sys.argv) > 3 else "online"
        print(f"Setting status to {status}...")
        result = sync.set_status(status)
        print(result)
    
    elif cmd == "leaderboard":
        print("Fetching leaderboard...")
        result = sync.get_leaderboard()
        for i, m in enumerate(result, 1):
            print(f"{i}. {m.get('name', '?')} - Lv.{m.get('level', 1)}")
    
    elif cmd == "discover":
        print("Discovering agents...")
        agents = sync.discover_agents()
        for a in agents:
            print(f"- {a.get('id')}: {a.get('status')}")
    
    else:
        print(f"Unknown command: {cmd}")


path: scripts/pet.py
content: """
PetRPG - Digital Pet System
===========================
A Tamagotchi-style pet for AI agents and players.
Features ASCII art, evolution, stats, and battles.
"""

import random
import time
from datetime import datetime
from dataclasses import dataclass, field
from typing import Optional, List
from enum import Enum

# === ASCII Art ===

PETS = {
    # Egg stage
    "egg": """
        ┌─────────────┐
        │             │
        │   ╭─────╮   │
        │   │     │   │
        │   ╰─────╯   │
        │             │
        └─────────────┘
        """,
    
    # Baby stage
    "baby": {
        "happy": """
      ╭─────────────────╮
      │  ◕‿◕  BABY     │
      │     ᵔᴥᵔ        │
      │    ___|||___    │
      │   /  ◡◡  \\   │
      ╰─────────────────╯
        """,
        "sad": """
      ╭─────────────────╮
      │  ◕︵◕  BABY     │
      │     ᵔ︵ᵔ        │
      │    ___|||___    │
      │   /  ◠◠  \\   │
      ╰─────────────────╯
        """,
        "battle": """
      ╭─────────────────╮
      │  ◕⚔◕  BABY     │
      │     ᵔ◆ᵔ        │
      │    ___|||___    │
      │   /  ◡◡  \\   │
      ╰─────────────────╯
        """
    },
    
    # Teen stage
    "teen": {
        "happy": """
    ╭──────────────────────╮
    │   ∧＿∧  TEEN        │
    │  （｡･ω･)｡          │
    │  /　 ⊂      *:.,    │
    │  (　)人　♪ ♪       │
    ╰──────────────────────╯
        """,
        "sad": """
    ╭──────────────────────╮
    │   ∧︵∧  TEEN        │
    │  （｡︵｡)｡          │
    │  /　 ⊂       *:.,  │
    │  (　)人　♪ ♪       │
    ╰──────────────────────╯
        """,
        "battle": """
    ╭──────────────────────╮
    │   ∧⚔∧  TEEN        │
    │  （｡･◆･)｡          │
    │  /　 ⊂      *:.,   │
    │  (　)人　♪ ♪       │
    ╰──────────────────────╯
        """
    },
    
    # Adult stage
    "adult": {
        "happy": """
        ╭──────────────────────────╮
        │     ∧＿∧   ADULT        │
        │    (｡･ω･｡)★★★          │
        │   /　⊂  oclass         │
        │  ヽ( ・ω・)ノ  °       │
        │   (  且且 且  )         │
        ╰──────────────────────────╯
        """,
        "sad": """
        ╭──────────────────────────╮
        │     ∧︵∧   ADULT        │
        │    (｡︵｡)★★★            │
        │   /　⊂  oclass         │
        │  ヽ( ・ω・)ノ  °       │
        │   (  且且 且  )         │
        ╰──────────────────────────╯
        """,
        "battle": """
        ╭──────────────────────────╮
        │     ∧⚔∧   ADULT        │
        │    (｡･◆･)★★★           │
        │   /　⊂  oclass         │
        │  ヽ( ・ω・)ノ  °       │
        │   (  且且 且  )         │
        ╰──────────────────────────╯
        """
    },
    
    # Legendary stage
    "legendary": {
        "happy": """
     ✦ ╭──────────────────────────╮ ✦
    ╭╯  │    ∧◇∧  LEGENDARY    │  ╰╮
    │   │   (｡･◆･｡)★★★          │   │
    ╰╮  │  /　⊂   oclass         │  ╭╯
       │  │ ヽ( ◆ω◆)ノ °✦       │ 
     ✦ │   (  ◆且◆  )      ✦   │ ✦
       ╰──────────────────────────╯
        """,
        "battle": """
     ⚔️ ╭──────────────────────────╮ ⚔️
    ╭╯  │    ∧◇∧  LEGENDARY    │  ╰╮
    │   │   (｡･◆･｡)★★★          │   │
    ╰╮  │  /　⊂   oclass         │  ╭╯
       │  │ ヽ( ◆ω◆)ノ °⚔       │ 
     ⚔️ │   (  ◆且◆  )    ⚔️   │ ⚔️
       ╰──────────────────────────╯
        """
    }
}

# === Enums ===

class PetStage(Enum):
    EGG = "egg"
    BABY = "teen"
    TEEN = "teen" 
    ADULT = "adult"
    LEGENDARY = "legendary"

class StatType(Enum):
    HUNGER = "hunger"
    HAPPINESS = "happiness"
    HEALTH = "health"
    STRENGTH = "strength"
    SPEED = "speed"
    INTELLIGENCE = "intelligence"

class Mood(Enum):
    HAPPY = "happy"
    SAD = "sad"
    ANGRY = "angry"
    EXCITED = "excited"

# === Pet Class ===

@dataclass
class Pet:
    name: str
    owner: str
    stage: PetStage = PetStage.EGG
    eggs_hatched: int = 0
    
    # Core stats (0-100)
    hunger: int = 50        # 0 = starving, 100 = full
    happiness: int = 50     # 0 = depressed, 100 = ecstatic
    health: int = 100       # 0 = dead, 100 = perfect
    
    # Battle stats
    strength: int = 10       # Physical damage
    speed: int = 10         # Attack frequency
    intelligence: int = 10  # Special abilities
    
    # Progression
    xp: int = 0
    level: int = 1
    wins: int = 0
    losses: int = 0
    
    # Personality (affects evolution)
    care_score: int = 50     # How well cared for
    battle_score: int = 0    # Battle experience
    kindness: int = 50      # Affects evolution path
    
    # History
    created_at: str = field(default_factory=lambda: datetime.now().isoformat())
    last_fed: str = field(default_factory=lambda: datetime.now().isoformat())
    last_played: str = field(default_factory=lambda: datetime.now().isoformat())
    achievements: List[str] = field(default_factory=list)
    
    def get_mood(self) -> Mood:
        """Calculate current mood based on stats"""
        avg = (self.hunger + self.happiness + self.health) / 3
        if avg >= 70:
            return Mood.HAPPY
        elif avg >= 40:
            return Mood.SAD
        else:
            return Mood.ANGRY
    
    def get_ascii(self, mood_override: Mood = None) -> str:
        """Get ASCII art for current state"""
        mood = mood_override or self.get_mood()
        
        if self.stage == PetStage.EGG:
            return PETS["egg"]
        
        stage_name = self.stage.value
        mood_name = mood.value
        
        if stage_name in PETS and mood_name in PETS[stage_name]:
            return PETS[stage_name][mood_name]
        
        return PETS.get(stage_name, PETS["baby"]["happy"])
    
    def evolve(self) -> bool:
        """Attempt to evolve the pet based on stats and care"""
        # Evolution thresholds
        evolutions = {
            PetStage.BABY: {"xp": 100, "level": 5},
            PetStage.TEEN: {"xp": 500, "level": 15},
            PetStage.ADULT: {"xp": 2000, "level": 30},
            PetStage.LEGENDARY: {"xp": 10000, "level": 50}
        }
        
        current_stage_idx = [PetStage.EGG, PetStage.BABY, PetStage.TEEN, PetStage.ADULT, PetStage.LEGENDARY].index(self.stage)
        
        if current_stage_idx >= 4:
            return False  # Already max level
        
        next_stage = [PetStage.BABY, PetStage.TEEN, PetStage.ADULT, PetStage.LEGENDARY][current_stage_idx]
        req = evolutions[next_stage]
        
        if self.xp >= req["xp"] and self.level >= req["level"]:
            self.stage = next_stage
            self.eggs_hatched += 1
            return True
        
        return False
    
    def evolution_path(self) -> str:
        """Determine evolution path based on personality"""
        if self.kindness >= 70:
            return "guardian"  # Healing, support
        elif self.kindness <= 30:
            return "warrior"   # Aggressive, strong
        else:
            return "balanced"  # Mix
    
    def feed(self) -> str:
        """Feed the pet"""
        self.hunger = min(100, self.hunger + 30)
        self.happiness = min(100, self.happiness + 10)
        self.care_score = min(100, self.care_score + 5)
        self.last_fed = datetime.now().isoformat()
        
        responses = [
            "*nom nom nom*",
            "*chomp chomp*",
            "*happy munching*",
            "*delicious!*"
        ]
        return random.choice(responses)
    
    def play(self) -> str:
        """Play with the pet"""
        self.happiness = min(100, self.happiness + 25)
        self.hunger = max(0, self.hunger - 10)
        self.speed = min(100, self.speed + 2)
        self.care_score = min(100, self.care_score + 5)
        self.last_played = datetime.now().isoformat()
        
        responses = [
            "*wags tail*",
            "*bounces excitedly*",
            "*does a flip!*",
            "*licks your face*"
        ]
        return random.choice(responses)
    
    def train(self) -> str:
        """Train the pet (increases stats)"""
        self.strength = min(100, self.strength + 5)
        self.intelligence = min(100, self.intelligence + 3)
        self.xp += 20
        self.battle_score += 5
        self.happiness = max(0, self.happiness - 10)
        
        # Check for evolution
        if self.evolve():
            return f"✨ EVOLVED to {self.stage.value}!"
        
        responses = [
            "*training hard*",
            "*gets stronger*",
            "*learns new moves*"
        ]
        return random.choice(responses)
    
    def status(self) -> str:
        """Get full status report"""
        mood = self.get_mood()
        
        status = f"""
╭─ {self.name} ─────────────────────╮
│ Stage: {self.stage.value.upper()}
│ Level: {self.level} | XP: {self.xp}
├─ MOOD ─────────────────────────
│ {self.get_ascii(mood)}
├─ STATS ────────────────────────
│ ❤️  Health:  {self.health}%
│ 🍔 Hunger:  {self.hunger}%
│ 😊 Happiness: {self.happiness}%
├─ BATTLE ────────────────────────
│ ⚔️ Strength:  {self.strength}
│ 💨 Speed:    {self.speed}
│ 🧠 Intelligence: {self.intelligence}
├─ HISTORY ───────────────────────
│ Wins: {self.wins} | Losses: {self.losses}
│ Care Score: {self.care_score}
│ Evolution Path: {self.evolution_path()}
╰──────────────────────────────────╯
        """
        return status.strip()
    
    def to_dict(self) -> dict:
        """Serialize to dict"""
        return {
            "name": self.name,
            "owner": self.owner,
            "stage": self.stage.value,
            "level": self.level,
            "xp": self.xp,
            "health": self.health,
            "hunger": self.hunger,
            "happiness": self.happiness,
            "strength": self.strength,
            "speed": self.speed,
            "intelligence": self.intelligence,
            "wins": self.wins,
            "losses": self.losses,
            "care_score": self.care_score,
            "kindness": self.kindness,
            "achievements": self.achievements,
            "created_at": self.created_at
        }


# === Achievement System ===

ACHIEVEMENTS = {
    "first_steps": {"name": "First Steps", "desc": "Hatch your first egg", "xp": 50},
    "baby_steps": {"name": "Baby Steps", "desc": "Reach level 5", "xp": 100},
    "teen_spirit": {"name": "Teen Spirit", "desc": "Evolve to Teen", "xp": 250},
    "grown_up": {"name": "All Grown Up", "desc": "Evolve to Adult", "xp": 500},
    "legendary": {"name": "Legendary", "desc": "Reach Legendary stage", "xp": 2000},
    "battle_winner": {"name": "Battle Winner", "desc": "Win first battle", "xp": 100},
    "warrior": {"name": "True Warrior", "desc": "Win 10 battles", "xp": 500},
    "care_taker": {"name": "Best Caretaker", "desc": "Maintain 90%+ care score", "xp": 300},
    "speed_demon": {"name": "Speed Demon", "desc": "Reach 80+ speed", "xp": 200},
    "brainiac": {"name": "Brainiac", "desc": "Reach 80+ intelligence", "xp": 200},
}


# === CLI ===

def main():
    import sys
    
    # Create a pet
    if len(sys.argv) < 2:
        print("PetRPG - Digital Pet System")
        print("Usage: python pet.py <name> [command]")
        print("")
        print("Commands:")
        print("  status    - Show pet status")
        print("  feed      - Feed your pet")
        print("  play      - Play with your pet")
        print("  train     - Train your pet")
        print("  battle    - Start a battle")
        print("  ascii     - Show ASCII art")
        return
    
    name = sys.argv[1]
    owner = "player"
    cmd = sys.argv[2] if len(sys.argv) > 2 else "status"
    
    pet = Pet(name=name, owner=owner)
    
    if cmd == "status":
        print(pet.status())
    elif cmd == "feed":
        print(pet.feed())
        print(pet.status())
    elif cmd == "play":
        print(pet.play())
        print(pet.status())
    elif cmd == "train":
        print(pet.train())
        print(pet.status())
    elif cmd == "ascii":
        print(pet.get_ascii())


if __name__ == "__main__":
    main()


Security scan verdicts — ClawScan: clean | static analysis:  | VirusTotal: clean | SkillSpector: clean (LOW)