diff --git a/.gitignore b/.gitignore index bbcf707e..a87a5e5f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,10 @@ rom/ # Screenshot output frames/ -# Tapes telemetry (SQLite DB + local config) +# Observer memory output (per-run observations + watermark) +pokedex/memory/ + +# Leftover local Tapes telemetry (project migrated to Paper) .tapes/ # Plans (ephemeral working artifacts, never commit) @@ -40,7 +43,12 @@ venv/ .coverage .pytest_cache/ -# Pokedex session logs (log7+ are local-only run artifacts) -pokedex/log[7-9]*.md -pokedex/log1[0-9]*.md -pokedex/log2[0-9]*.md +# Pokedex session logs: log1-6 are committed as examples, everything +# else is local-only run output (users do their own training runs). +pokedex/log*.md +!pokedex/log1.md +!pokedex/log2.md +!pokedex/log3.md +!pokedex/log4.md +!pokedex/log5.md +!pokedex/log6.md diff --git a/README.md b/README.md index f7b68883..a5ab6a7f 100644 --- a/README.md +++ b/README.md @@ -20,27 +20,27 @@ stereOS VM (/workspace) │ ↓ button inputs │ │ GameController → PyBoy │ │ │ -│ Tapes ← proxies LLM API calls, records sessions │ +│ paperd ← proxies LLM API calls, records sessions│ │ │ └──────────────────────────────────────────────────┘ ↕ shared mount (./ ↔ /workspace) -Host: frames/ .tapes/ pokedex/ +Host: frames/ pokedex/ ``` The agent runs a tight loop: read game state from known memory addresses, pick an action, send button inputs, tick the emulator forward. No display server needed. Screenshots come from PyBoy's internal frame buffer (`screen.ndarray`), not from the OS. -**Shared mount permissions.** The `[[shared]]` mount in `jcard.toml` maps `./` on the host to `/workspace` in the VM. Files keep their host ownership (UID 501 on macOS), but the VM runs as `admin` (UID 1000). This means host-created directories are read-only inside the VM by default. The install script opens write permissions on output directories (`frames/`, `pokedex/`, `.tapes/`) so the agent can write session data that persists back to the host. +**Shared mount permissions.** The `[[shared]]` mount in `jcard.toml` maps `./` on the host to `/workspace` in the VM. Files keep their host ownership (UID 501 on macOS), but the VM runs as `admin` (UID 1000). This means host-created directories are read-only inside the VM by default. The install script opens write permissions on output directories (`frames/`, `pokedex/`) so the agent can write session data that persists back to the host. ## Quickstart ### stereOS (recommended) ```bash -mb up # boot the VM, install deps, start the agent through Tapes +mb up # boot the VM, install deps, start the agent through Paper mb attach # watch it play ``` -The VM configuration lives in `jcard.toml`. It mounts the repo at `/workspace`, installs Python + PyBoy + Tapes, and runs the agent. +The VM configuration lives in `jcard.toml`. It mounts the repo at `/workspace`, installs Python + PyBoy, and runs the agent. `paperd` is assumed to be running on the host (authenticate the `paper` CLI with `paper status` first); it proxies the agents' LLM calls via `ANTHROPIC_BASE_URL`. ### Local @@ -63,32 +63,22 @@ Add `--save-screenshots` to capture frames every 10 turns into `frames/`. **Overworld navigation.** Outside battle, the agent follows waypoints defined in `references/routes.json`. It handles early-game scripted sequences (Red's room to Oak's lab) and general map-to-map routing. A stuck counter triggers random movement to break out of loops. -## Tapes Telemetry +## Paper Telemetry -Tapes proxies all LLM API calls made by the agent and records them with content-addressable session storage. The install script sets up Tapes automatically inside the VM. +[Paper](https://papercompute.com) records every LLM session the agent runs. The local `paperd` daemon proxies all API calls transparently (via `ANTHROPIC_BASE_URL`) — no instrumentation in the agent code. Each agent session appears in the Paper dashboard with its own session ID, turn count, and cost. -After a run, inspect what happened: - -```bash -tapes deck # terminal UI for session exploration -tapes search "battle" # search session turns -tapes checkout # restore a previous conversation state -``` - -Session data lives in `.tapes/` (gitignored). +When the multi-agent runner spawns variants via `paper start claude`, each one is a full, independently recorded Claude Code session. Authenticate the `paper` CLI once with `paper status` before launching. ## Observational Memory -Inspired by [Mastra's observational memory](https://mastra.ai/blog/observational-memory), this system reads the [Tapes](https://tapes.dev) SQLite database, extracts noteworthy events via heuristic pattern matching (no LLM calls), and writes prioritized observations to memory files. +Inspired by [Mastra's observational memory](https://mastra.ai/blog/observational-memory), this system reads recorded Paper sessions, extracts noteworthy events via heuristic pattern matching (no LLM calls), and writes prioritized observations to memory files. -Tapes records every LLM conversation as a content-addressable DAG of nodes in `.tapes/tapes.sqlite`. The observer walks these conversation chains, identifies patterns (errors, file creations, token usage), and writes observations alongside the database. +`paper_reader.py` is a two-source hybrid: it discovers sessions through the local paperd API (filtered to this working directory) and reads their transcript content from the Claude Code JSONL files under `~/.claude/projects/`. When paperd is unavailable, it falls back to scanning the JSONL directory directly, so observation still works offline. The observer walks each session, identifies patterns (errors, file creations, token usage), and writes observations to `pokedex/memory/`. ``` -.tapes/ -├── tapes.sqlite # Tapes DB: nodes, embeddings, facets -└── memory/ - ├── observations.md # date-grouped observations with priority tags - └── observer_state.json # watermark tracking processed sessions +pokedex/memory/ +├── observations.md # date-grouped observations with priority tags +└── observer_state.json # watermark tracking processed sessions ``` **What it extracts:** @@ -109,11 +99,11 @@ uv run scripts/observe_cli.py # Reprocess everything from scratch uv run scripts/observe_cli.py --reset -# Process a single session by root node hash -uv run scripts/observe_cli.py --session +# Process a single session by ID +uv run scripts/observe_cli.py --session ``` -Auto-detects `.tapes/tapes.sqlite` from cwd. Override with `--db`. +Sessions are discovered from paperd (read from `ANTHROPIC_BASE_URL`), or from the local JSONL transcripts when paperd is offline. The watermark in `observer_state.json` is stamped with the reader identity and auto-resets if the reader changes, so upgrades don't reprocess old sessions. ## AlphaEvolve Strategy Evolution @@ -152,15 +142,14 @@ pokemon-agent/ ├── CONTRIBUTING.md # contributor guide ├── SKILL.md # skill definition for stereOS agents ├── jcard.toml # stereOS VM configuration -├── .tapes/ # Tapes telemetry DB + config (gitignored) ├── frames/ # screenshot output (gitignored) ├── rom/ # user-provided ROM files (gitignored) ├── scripts/ -│ ├── install.sh # setup: Python, PyBoy, Tapes +│ ├── install.sh # setup: Python, PyBoy, checks paperd │ ├── agent.py # main agent loop + strategies │ ├── memory_reader.py # memory address definitions │ ├── memory_file.py # agent memory management -│ ├── tape_reader.py # Tapes SQLite reader (stdlib only) +│ ├── paper_reader.py # Paper API + JSONL transcript reader (stdlib only) │ ├── observer.py # heuristic observation extractor │ ├── observe_cli.py # CLI for running the observer │ ├── pathfinding.py # collision map + backtrack manager diff --git a/SKILL.md b/SKILL.md index f346cadb..bd67ae08 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,253 +1,175 @@ --- name: pokemon-agent description: "Play turn-based RPGs autonomously via Game Boy emulation. Use when the user asks to 'play pokemon', 'emulate a game boy game', 'automate pokemon battles', 'grind pokemon', 'run a pokemon nuzlocke', 'play an RPG for me', or mentions headless emulation, PyBoy, or turn-based game automation." -version: 0.1.0 +version: 0.2.0 metadata: - { "openclaw": { "emoji": "🎮", "requires": { "bins": ["python3"], "env": [] }, "install": [{ "id": "pip", "kind": "node", "label": "Install PyBoy + dependencies (pip)" }] } } + { "openclaw": { "emoji": "🎮", "requires": { "bins": ["python3", "paper"], "env": [] }, "install": [{ "id": "pip", "kind": "node", "label": "Install PyBoy + dependencies (pip)" }] } } --- # Pokemon Agent Autonomous turn-based RPG player using headless Game Boy emulation via PyBoy. - -## Overview - -This skill runs a Game Boy / Game Boy Color ROM headlessly using PyBoy's Python API. The agent reads game state from emulator memory, makes strategic decisions (via LLM or heuristics), and sends button inputs back. No display server required — runs fully headless inside a terminal, container, or stereOS VM. +Sessions are recorded via Paper — every API call is captured and observable. ## Requirements -- Python 3.10+ -- PyBoy (`pip install pyboy`) +- Python 3.10+ with PyBoy (`pip install pyboy Pillow numpy`) +- `paper` CLI authenticated (`paper status`) - A legally obtained ROM file (`.gb` or `.gbc`) -- Optional: `Pillow` for screenshot capture and frame export ## Setup -Run the install script to set up the Python environment: - ```bash cd {baseDir} bash scripts/install.sh ``` -Place your ROM file in the skill directory or provide an absolute path when starting. - -## Usage - -### Start a game session +## Running a single agent -``` -Play Pokemon Red for me -Start a new pokemon playthrough -Grind my team on Route 3 +```bash +~/venv/bin/python3 scripts/agent.py 'rom/Pokemon - Red Version (USA, Europe) (SGB Enhanced).gb' \ + --strategy low --max-turns 5000 ``` -### Battle automation +When run via `paper start claude`, this session is automatically recorded in Paper. -``` -Auto-battle wild encounters -Use the best move against the current opponent -Grind until my starter reaches level 16 -``` +## Running the multi-agent evolution loop -### Navigation +`run_10_agents.py` spawns one `paper start claude` process per parameter variant. +Each agent is a full Claude Code session — independently recorded, scoreable, observable. +```bash +paper start claude -- --print --dangerously-skip-permissions \ + "Run the Pokemon agent evolution loop: python3 scripts/run_10_agents.py \ + 'rom/Pokemon - Red Version (USA, Europe) (SGB Enhanced).gb'" ``` -Walk to Pewter City -Navigate to the next gym -Find and heal at the nearest Pokemon Center -``` - -## How It Works - -### Game Loop -1. **Boot**: Launch PyBoy in headless mode (`window="null"`) -2. **Read state**: Extract game data from known memory addresses -3. **Decide**: Choose action based on current context (battle, overworld, menu) -4. **Act**: Send button inputs to the emulator -5. **Advance**: Tick the emulator forward, wait for state change -6. **Repeat** - -### Memory Map (Pokemon Red/Blue) +Or directly from the host (paperd must be running): -The agent reads game state from these memory addresses: - -| Address | Data | -|---------|------| -| `0xD057` | Battle type (0 = none, 1 = wild, 2 = trainer) | -| `0xCFE6` | Enemy current HP | -| `0xCFE7` | Enemy max HP | -| `0xD015` | Player lead Pokemon current HP (high byte) | -| `0xD016` | Player lead Pokemon current HP (low byte) | -| `0xD014` | Player lead Pokemon level | -| `0xD163` | Number of Pokemon in party | -| `0xD01C` | Player Pokemon move 1 ID | -| `0xD01D` | Player Pokemon move 2 ID | -| `0xD01E` | Player Pokemon move 3 ID | -| `0xD01F` | Player Pokemon move 4 ID | -| `0xD02C` | Player Pokemon move 1 PP | -| `0xD02D` | Player Pokemon move 2 PP | -| `0xD35E` | Current map ID | -| `0xD361` | Player X position | -| `0xD362` | Player Y position | -| `0xD31D` | Number of badges | -| `0xFF44` | Current scanline (use to detect vblank for frame sync) | - -### Battle Strategy - -When in battle (`0xD057 != 0`): - -1. Read enemy HP and player HP -2. If player HP < 20% max → use best healing item -3. If all moves have PP → pick highest-power move with type advantage -4. If a move is super effective → always prefer it -5. If no PP remaining → use Struggle (auto-selected) -6. If player fainted → switch to next alive Pokemon -7. If all fainted → navigate to Pokemon Center after whiteout - -### Overworld Navigation - -When not in battle (`0xD057 == 0`): +```bash +python3 scripts/run_10_agents.py 'rom/Pokemon - Red Version (USA, Europe) (SGB Enhanced).gb' +``` -1. Read current map ID and position -2. Follow a predefined route plan (stored in `references/routes.json`) -3. Move toward objective using cardinal directions -4. If grass tile → expect random encounter, ensure party is healthy -5. If at Pokemon Center → heal if any party member below 50% -6. If at objective → execute next story beat +Each sub-agent receives a prompt like: -### Input Mapping +> Run the Pokemon agent with the parameters below and print the fitness JSON. +> `EVOLVE_PARAMS='{"stuck_threshold": 8, ...}' ~/venv/bin/python3 scripts/agent.py ...` +> When it finishes, read the output JSON and print ONLY its raw JSON contents as the final line. -Send inputs via PyBoy's button API: +The orchestrator parses each agent's fitness from stdout, ranks by score, and saves results to `pokedex/evolve_results.json`. -```python -# Button press: hold for N frames then release -def press_button(pyboy, button, frames=10): - pyboy.button(button) # press - for _ in range(frames): - pyboy.tick() - pyboy.button_release(button) # release - pyboy.tick() - -# Available buttons: "a", "b", "start", "select", "up", "down", "left", "right" -``` +## When invoked as a sub-agent by run_10_agents.py -### Menu Navigation +You will receive a prompt containing: +1. An `EVOLVE_PARAMS` JSON blob with navigator parameters +2. A bash command to run `agent.py` with `--output-json /tmp/pokemon_fitness_