"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: add Slay the Spire II CLI harness
yuhao67878d525c95
diff --git a/.gitignore b/.gitignoreindex 8afe11ee9..f4832a034 100644--- a/.gitignore+++ b/.gitignore@@ -56,6 +56,7 @@!/musescore/!/krita/!/iterm2/+!/slay_the_spire_ii/# Step 5: Inside each software dir, ignore everything (including dotfiles)/gimp/*@@ -100,6 +101,8 @@/krita/.*/iterm2/*/iterm2/.*+/slay_the_spire_ii/*+/slay_the_spire_ii/.*# Step 6: ...except agent-harness/!/gimp/agent-harness/@@ -124,6 +127,8 @@!/musescore/agent-harness/!/krita/agent-harness/!/iterm2/agent-harness/+!/slay_the_spire_ii/agent-harness/+!/slay_the_spire_ii/README.md# Step 7: Ignore build artifacts within allowed dirs**/__pycache__/diff --git a/slay_the_spire_ii/README.md b/slay_the_spire_ii/README.mdnew file mode 100644index 000000000..9f66b3091--- /dev/null+++ b/slay_the_spire_ii/README.md@@ -0,0 +1,214 @@+# CLI-Anything-Slay-the-Spire-2++`CLI-Anything-Slay-the-Spire-2` is a CLI harness that connects the real Steam version of *Slay the Spire 2* to a stateful command-line interface, making it agent-native.++<p align="center">+ <img src="assets/example_gif.gif" alt="CLI-Anything-Slay-the-Spire-2 demo" width="900">+</p>++It works like this:++1. The in-game bridge mod `STS2_Bridge` runs inside the game process.+2. The mod exposes a local HTTP API at `http://localhost:15526/api/v1/singleplayer`.+3. The CLI reads state and sends actions through that API.++This project controls the real running game. It is not a headless simulator and it does not use screen automation.++## What Is Included++- `agent-harness/`+ - The CLI harness package (`cli_anything/slay_the_spire_ii/`), installable via `pip install -e .`.+- `bridge/plugin/`+ - `.NET 9` source for the bridge mod. **This mod is required** — the CLI cannot function without it.+- `bridge/install/`+ - Install bundle and scripts for the bridge mod.++**Important:** Unlike other CLI-Anything harnesses that wrap standalone applications, this harness requires a custom bridge mod to be built and installed into the game. The bridge mod exposes the game's internal state via HTTP, which the CLI then consumes.++## Requirements++- A working Steam installation of *Slay the Spire 2*+- Python `>= 3.10`+- `.NET 9 SDK` (only for building the bridge mod)++The bridge build and install scripts currently auto-detect the default macOS Steam path. If your game is installed elsewhere, pass the path explicitly or override it with an environment variable.++## Installation++### 1. Install the CLI++From the `agent-harness/` directory:++```bash+cd agent-harness+pip install -e .+```++This installs the `cli-anything-sts2` command.++### 2. Build the bridge mod++```bash+cd bridge/plugin+./build.sh+```++The script tries to auto-detect the game data directory and refreshes the local install bundle at:++```text+bridge/install/bridge_plugin/+```++If auto-detection fails, set `STS2_GAME_DATA_DIR` or pass the directory directly:++```bash+STS2_GAME_DATA_DIR="/path/to/data_sts2_macos_arm64" ./build.sh+```++The target directory must contain at least:++- `sts2.dll`+- `GodotSharp.dll`+- `0Harmony.dll`++### 3. Install the bridge mod into the game++```bash+cd bridge/install+./install_bridge.sh+```++The default target path is:++```text+~/Library/Application Support/Steam/steamapps/common/Slay the Spire 2/SlayTheSpire2.app/Contents/MacOS/mods/STS2_Bridge/+```++If your game is not installed in the default location, pass the game root explicitly:++```bash+./install_bridge.sh "/path/to/Slay the Spire 2"+```++### 4. Enable the mod in game++Launch the game and make sure `STS2_Bridge` is loaded and enabled. Once enabled, the mod listens on:++```text+http://localhost:15526/+```++### 5. Verify the setup++```bash+cli-anything-sts2 --help+cli-anything-sts2 state+```++If `cli-anything-sts2 state` returns JSON, the CLI and the bridge are connected correctly.++## Usage++### Shortest path++1. Build and install `STS2_Bridge`+2. Launch the real game and enable the mod+3. Run `pip install -e .` from the `agent-harness/` directory+4. Run `cli-anything-sts2 state`++### Start from the main menu++```bash+cli-anything-sts2 state+cli-anything-sts2 continue-game+cli-anything-sts2 start-game --character IRONCLAD --ascension 0+cli-anything-sts2 abandon-game+cli-anything-sts2 return-to-main-menu+```++`start-game --character` currently recognizes:++- `IRONCLAD`+- `SILENT`+- `DEFECT`+- `NECROBINDER`+- `REGENT`++### Manual control during a run++```bash+cli-anything-sts2 state+cli-anything-sts2 choose-map 0+cli-anything-sts2 play-card 0 --target jaw_worm_0+cli-anything-sts2 end-turn+cli-anything-sts2 claim-reward 0+cli-anything-sts2 pick-card-reward 0+cli-anything-sts2 rest 0+cli-anything-sts2 event 0+cli-anything-sts2 repl+```++Common command groups:++- State inspection: `state`, `raw-state`+- Menu actions: `continue-game`, `start-game`, `abandon-game`, `return-to-main-menu`+- Combat: `play-card`, `use-potion`, `end-turn`+- Map and rooms: `choose-map`, `event`, `advance-dialogue`, `rest`, `proceed`+- Rewards and overlays: `claim-reward`, `pick-card-reward`, `skip-card-reward`, `select-card`, `confirm-selection`, `select-relic`++For the full command surface:++```bash+cli-anything-sts2 --help+```++## Configuration++### CLI++- `--base-url`+ - Default: `http://localhost:15526`+- `--timeout`+ - Default: `10.0`++Example:++```bash+cli-anything-sts2 --base-url http://127.0.0.1:15526 --timeout 20 state+```++### Bridge build++- `STS2_GAME_DATA_DIR`+ - Use this when `bridge/plugin/build.sh` cannot auto-detect the game data directory++## Troubleshooting++### `cli-anything-sts2 state` cannot connect++This usually means one of the following is still missing:++- The game is not running+- `STS2_Bridge` is not installed or not enabled+- The local API on `localhost:15526` is not up yet++### `bridge/plugin/build.sh` cannot find the game directory++Confirm that the game is installed, then pass `STS2_GAME_DATA_DIR` explicitly:++```bash+STS2_GAME_DATA_DIR="/path/to/data_sts2_macos_arm64" ./bridge/plugin/build.sh+```++## Related Docs++- [agent-harness/STS2.md](agent-harness/STS2.md)+- [bridge/plugin/README.md](bridge/plugin/README.md)++## Credits++This project was informed by:++- [`wuhao21/sts2-cli`](https://github.com/wuhao21/sts2-cli)+- [`Gennadiyev/STS2MCP`](https://github.com/Gennadiyev/STS2MCP)+- [`HKUDS/CLI-Anything`](https://github.com/HKUDS/CLI-Anything)diff --git a/slay_the_spire_ii/agent-harness/STS2.md b/slay_the_spire_ii/agent-harness/STS2.mdnew file mode 100644index 000000000..f58cbf1b3--- /dev/null+++ b/slay_the_spire_ii/agent-harness/STS2.md@@ -0,0 +1,63 @@+# Slay the Spire 2: Project-Specific Analysis & SOP++## Architecture Summary++Slay the Spire 2 is a real-time roguelike deckbuilder running as a native+Steam game. Unlike other CLI-Anything harnesses that wrap desktop applications+via subprocess, this harness communicates with a live game process through an+in-game bridge mod (`STS2_Bridge`) that exposes a local HTTP API.++```+┌────────────────────────────────────────────┐+│ Slay the Spire 2 (Steam) │+│ ┌──────────┐ ┌──────────┐ ┌─────────┐ │+│ │ Combat │ │ Map │ │ Menu │ │+│ └─────┬────┘ └────┬─────┘ └────┬────┘ │+│ │ │ │ │+│ ┌─────┴─────────────┴─────────────┴─────┐ │+│ │ STS2_Bridge (.NET mod) │ │+│ │ Reads game state, executes actions │ │+│ └──────────────────┬────────────────────┘ │+│ │ │+│ http://localhost:15526 │+└─────────────────────┼──────────────────────┘+ │+ ┌─────────────┴────────────────┐+ │ cli-anything-sts2 │+ │ state · play-card · rest … │+ └──────────────────────────────┘+```++## CLI Strategy: HTTP Bridge + Normalized State++The CLI communicates with the bridge mod over HTTP at+`localhost:15526/api/v1/singleplayer`. It reads normalized JSON state and+sends action commands back through the same endpoint.++### Core Domains++| Domain | Module | Key Operations |+|--------|--------|----------------|+| State | `state_adapter.py` | Normalize raw bridge JSON into decision-based state |+| Actions | `action_adapter.py` | Build typed action payloads for every game command |+| Backend | `sts2_backend.py` | HTTP client wrapping GET/POST to the bridge API |+| Types | `types.py` | `JsonDict` type alias, `PlannedAction` dataclass |++### Decision States++The bridge normalizes all game screens into one of 14 decision types:++`menu` · `combat_play` · `hand_select` · `map_select` · `game_over` ·+`combat_rewards` · `card_reward` · `event_choice` · `rest_site` · `shop` ·+`card_select` · `relic_select` · `treasure` · `overlay` · `unknown`++### Characters++`IRONCLAD` · `SILENT` · `DEFECT` · `NECROBINDER` · `REGENT`++## Backend: Low Translation Gap++The bridge mod has direct access to the game's internal state and action API.+The CLI translates cleanly to HTTP calls. The only requirement is that the+game must be running with the `STS2_Bridge` mod enabled and listening on+`localhost:15526`.diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/README.md b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/README.mdnew file mode 100644index 000000000..805d7c0d0--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/README.md@@ -0,0 +1,204 @@+# cli-anything-slay-the-spire-ii++A stateful command-line interface for controlling the real Slay the Spire 2+game through the local `STS2_Bridge` mod. Reads normalized game state and+sends action commands via a local HTTP API.++## Installation++This CLI is installed as part of the cli-anything-slay-the-spire-ii package:++```bash+pip install cli-anything-slay-the-spire-ii+```++**Prerequisites:**+- Python 3.10++- Slay the Spire 2 (Steam) with `STS2_Bridge` mod installed and enabled+- The bridge mod listening on `http://localhost:15526`++## Usage++### Basic Commands++```bash+# Show help+cli-anything-sts2 --help++# Start interactive REPL mode+cli-anything-sts2 repl++# Read normalized game state+cli-anything-sts2 state++# Read raw bridge JSON+cli-anything-sts2 raw-state+```++### REPL Mode++When invoked with the `repl` subcommand, the CLI enters an interactive session:++```bash+cli-anything-sts2 repl+# Enter commands interactively:+# sts2> state+# sts2> play-card 0 --target jaw_worm_0+# sts2> end-turn+```++## Command Groups++### State Inspection++| Command | Description |+|---------|-------------|+| `state` | Print normalized game state with `decision` field |+| `raw-state` | Print raw bridge-plugin JSON |++### Main Menu++| Command | Description |+|---------|-------------|+| `continue-game` | Continue a saved run |+| `start-game --character IRONCLAD --ascension 0` | Start a new run |+| `abandon-game` | Abandon the current save |+| `return-to-main-menu` | Return to the main menu |++### Combat++| Command | Description |+|---------|-------------|+| `play-card <index> [--target <enemy_id>]` | Play a card from hand |+| `use-potion <slot> [--target <enemy_id>]` | Use a potion |+| `end-turn` | End the current turn |++### Map & Room Flow++| Command | Description |+|---------|-------------|+| `choose-map <index>` | Select a map node |+| `proceed` | Leave the current room |++### Rewards++| Command | Description |+|---------|-------------|+| `claim-reward <index>` | Claim a combat reward |+| `pick-card-reward <index>` | Pick a card reward |+| `skip-card-reward` | Skip the card reward |+| `claim-treasure-relic <index>` | Claim a treasure relic |+| `select-relic <index>` | Select a relic |+| `skip-relic-selection` | Skip relic selection |++### Events & Rest Sites++| Command | Description |+|---------|-------------|+| `event <index>` | Choose an event option |+| `advance-dialogue` | Advance dialogue-only events |+| `rest <index>` | Choose a campfire action |++### Shop++| Command | Description |+|---------|-------------|+| `shop-buy <index>` | Buy an item from the shop |++### Card/Relic Selection Overlays++| Command | Description |+|---------|-------------|+| `select-card <index>` | Select a card in overlay |+| `confirm-selection` | Confirm the current selection |+| `cancel-selection` | Cancel the current selection |+| `combat-select-card <index>` | Select a card during combat overlay |+| `combat-confirm-selection` | Confirm combat card selection |++### Raw Action++| Command | Description |+|---------|-------------|+| `action <name> --kv key=value` | Send a raw action with payload |++## Examples++### Start a New Run++```bash+cli-anything-sts2 start-game --character IRONCLAD --ascension 0+cli-anything-sts2 state+```++### Play Through Combat++```bash+cli-anything-sts2 state # Check game state+cli-anything-sts2 play-card 0 --target jaw_worm_0 # Play first card+cli-anything-sts2 state # Re-check after play+cli-anything-sts2 end-turn # End turn+```++### Navigate Map and Events++```bash+cli-anything-sts2 choose-map 0 # Pick a map node+cli-anything-sts2 event 1 # Choose event option+cli-anything-sts2 rest 0 # Rest at campfire+```++### Interactive REPL Session++```bash+cli-anything-sts2 repl+# sts2> state+# sts2> play-card 2+# sts2> end-turn+# sts2> exit+```++## Configuration++| Option | Default | Description |+|--------|---------|-------------|+| `--base-url` | `http://localhost:15526` | Bridge API URL |+| `--timeout` | `10.0` | HTTP timeout in seconds |++## Architecture++```+cli_anything/slay_the_spire_ii/+├── __init__.py+├── __main__.py # python3 -m cli_anything.slay_the_spire_ii+├── slay_the_spire_ii_cli.py # CLI entry point (argparse + REPL)+├── core/+│ ├── __init__.py+│ ├── action_adapter.py # Action payload factories+│ ├── state_adapter.py # Raw → normalized state mapping+│ └── types.py # JsonDict, PlannedAction+├── utils/+│ ├── __init__.py+│ ├── sts2_backend.py # HTTP client for the bridge API+│ └── repl_skin.py # Shared REPL interface+└── skills/+ └── SKILL.md # Skill definition for AI agents+```++## For AI Agents++When using this CLI programmatically:++1. **Always read `state` first** to get the current `decision` field+2. **Check return codes** - 0 for success, non-zero for errors+3. **Parse stdout** for JSON output+4. **Re-read state after each action** - hand indices and energy change during combat+5. **Use absolute paths** for any file operations++## More Information++- Architecture: See STS2.md in the agent-harness root+- Methodology: See HARNESS.md in the cli-anything-plugin++## Version++1.0.0diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/__init__.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/__init__.pynew file mode 100644index 000000000..a3b11547b--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/__init__.py@@ -0,0 +1,5 @@+"""Slay the Spire 2 CLI - A stateful CLI for controlling the real STS2 game."""++__all__ = ["__version__"]++__version__ = "1.0.0"diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/__main__.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/__main__.pynew file mode 100644index 000000000..d0b80ac67--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/__main__.py@@ -0,0 +1,4 @@+"""Allow running as python3 -m cli_anything.slay_the_spire_ii"""+from cli_anything.slay_the_spire_ii.slay_the_spire_ii_cli import main++raise SystemExit(main())diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/__init__.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/__init__.pynew file mode 100644index 000000000..faabfc27f--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/__init__.py@@ -0,0 +1 @@+"""Core domain logic for Slay the Spire 2 CLI."""diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/action_adapter.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/action_adapter.pynew file mode 100644index 000000000..5eec0657a--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/action_adapter.py@@ -0,0 +1,139 @@+from __future__ import annotations++from .types import JsonDict+++def play_card(card_index: int, target: str | None = None) -> JsonDict:+ payload: JsonDict = {"action": "play_card", "card_index": card_index}+ if target is not None:+ payload["target"] = target+ return payload+++def use_potion(slot: int, target: str | None = None) -> JsonDict:+ payload: JsonDict = {"action": "use_potion", "slot": slot}+ if target is not None:+ payload["target"] = target+ return payload+++def end_turn() -> JsonDict:+ return {"action": "end_turn"}+++def choose_map_node(index: int) -> JsonDict:+ return {"action": "choose_map_node", "index": index}+++def choose_event_option(index: int) -> JsonDict:+ return {"action": "choose_event_option", "index": index}+++def advance_dialogue() -> JsonDict:+ return {"action": "advance_dialogue"}+++def choose_rest_option(index: int) -> JsonDict:+ return {"action": "choose_rest_option", "index": index}+++def shop_purchase(index: int) -> JsonDict:+ return {"action": "shop_purchase", "index": index}+++def claim_reward(index: int) -> JsonDict:+ return {"action": "claim_reward", "index": index}+++def select_card_reward(card_index: int) -> JsonDict:+ return {"action": "select_card_reward", "card_index": card_index}+++def skip_card_reward() -> JsonDict:+ return {"action": "skip_card_reward"}+++def proceed() -> JsonDict:+ return {"action": "proceed"}+++def select_card(index: int) -> JsonDict:+ return {"action": "select_card", "index": index}+++def confirm_selection() -> JsonDict:+ return {"action": "confirm_selection"}+++def cancel_selection() -> JsonDict:+ return {"action": "cancel_selection"}+++def combat_select_card(card_index: int) -> JsonDict:+ return {"action": "combat_select_card", "card_index": card_index}+++def combat_confirm_selection() -> JsonDict:+ return {"action": "combat_confirm_selection"}+++def select_relic(index: int) -> JsonDict:+ return {"action": "select_relic", "index": index}+++def skip_relic_selection() -> JsonDict:+ return {"action": "skip_relic_selection"}+++def claim_treasure_relic(index: int) -> JsonDict:+ return {"action": "claim_treasure_relic", "index": index}+++def continue_game() -> JsonDict:+ return {"action": "continue_game"}+++def start_new_game(character: str = "IRONCLAD", ascension: int = 0) -> JsonDict:+ return {"action": "start_new_game", "character": character, "ascension": ascension}+++def abandon_game() -> JsonDict:+ return {"action": "abandon_game"}+++def return_to_main_menu() -> JsonDict:+ return {"action": "return_to_main_menu"}+++def from_name(name: str, **kwargs: object) -> JsonDict:+ factories = {+ "play_card": play_card,+ "use_potion": use_potion,+ "end_turn": end_turn,+ "choose_map_node": choose_map_node,+ "choose_event_option": choose_event_option,+ "advance_dialogue": advance_dialogue,+ "choose_rest_option": choose_rest_option,+ "shop_purchase": shop_purchase,+ "claim_reward": claim_reward,+ "select_card_reward": select_card_reward,+ "skip_card_reward": skip_card_reward,+ "proceed": proceed,+ "select_card": select_card,+ "confirm_selection": confirm_selection,+ "cancel_selection": cancel_selection,+ "combat_select_card": combat_select_card,+ "combat_confirm_selection": combat_confirm_selection,+ "select_relic": select_relic,+ "skip_relic_selection": skip_relic_selection,+ "claim_treasure_relic": claim_treasure_relic,+ "continue_game": continue_game,+ "start_new_game": start_new_game,+ "abandon_game": abandon_game,+ "return_to_main_menu": return_to_main_menu,+ }+ try:+ factory = factories[name]+ except KeyError as exc:+ raise ValueError(f"Unknown action name: {name}") from exc+ return factory(**kwargs)diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/state_adapter.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/state_adapter.pynew file mode 100644index 000000000..b36b6eb8c--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/state_adapter.py@@ -0,0 +1,287 @@+from __future__ import annotations++from typing import Any++from .types import JsonDict+++def normalize_state(raw_state: JsonDict) -> JsonDict:+ state_type = str(raw_state.get("state_type") or "unknown")+ run = _copy_dict(raw_state.get("run"))+ context = {+ "act": run.get("act"),+ "floor": run.get("floor"),+ "ascension": run.get("ascension"),+ }++ if state_type in {"monster", "elite", "boss"}:+ return _normalize_combat(raw_state, state_type, context)+ if state_type == "hand_select":+ return _normalize_hand_select(raw_state, context)+ if state_type == "card_reward":+ return _normalize_card_reward(raw_state, context)+ if state_type == "combat_rewards":+ return _normalize_combat_rewards(raw_state, context)+ if state_type == "map":+ return _normalize_map(raw_state, context)+ if state_type == "event":+ return _normalize_event(raw_state, context)+ if state_type == "rest_site":+ return _normalize_rest_site(raw_state, context)+ if state_type == "shop":+ return _normalize_shop(raw_state, context)+ if state_type == "card_select":+ return _normalize_card_select(raw_state, context)+ if state_type == "relic_select":+ return _normalize_relic_select(raw_state, context)+ if state_type == "treasure":+ return _normalize_treasure(raw_state, context)+ if state_type == "game_over":+ return _normalize_game_over(raw_state, context)+ if state_type == "menu":+ menu = _copy_dict(raw_state.get("menu"))+ return {+ "type": "status",+ "decision": "menu",+ "context": context,+ "run": run,+ "message": raw_state.get("message"),+ "screen": menu.get("screen"),+ "can_continue_game": menu.get("can_continue_game", False),+ "can_start_new_game": menu.get("can_start_new_game", False),+ "can_abandon_game": menu.get("can_abandon_game", False),+ "characters": _copy_list(menu.get("characters")),+ "ascension": menu.get("ascension"),+ "menu": menu,+ }+ if state_type == "overlay":+ return {+ "type": "status",+ "decision": "overlay",+ "context": context,+ "run": run,+ "overlay": _copy_dict(raw_state.get("overlay")),+ }+ return {+ "type": "status",+ "decision": "unknown",+ "context": context,+ "run": run,+ "raw_state_type": state_type,+ "message": raw_state.get("message"),+ "raw": raw_state,+ }+++def _normalize_combat(raw_state: JsonDict, state_type: str, context: JsonDict) -> JsonDict:+ battle = _copy_dict(raw_state.get("battle"))+ player = _copy_dict(battle.get("player"))+ return {+ "type": "decision",+ "decision": "combat_play",+ "room_type": state_type,+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "round": battle.get("round"),+ "turn": battle.get("turn"),+ "is_play_phase": battle.get("is_play_phase"),+ "energy": player.get("energy", 0),+ "max_energy": player.get("max_energy", 0),+ "hand": _copy_list(player.get("hand")),+ "enemies": _copy_list(battle.get("enemies")),+ "player": player,+ "draw_pile_count": player.get("draw_pile_count", 0),+ "discard_pile_count": player.get("discard_pile_count", 0),+ "exhaust_pile_count": player.get("exhaust_pile_count", 0),+ "battle": battle,+ }+++def _normalize_hand_select(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ hand_select = _copy_dict(raw_state.get("hand_select"))+ battle = _copy_dict(raw_state.get("battle"))+ player = _copy_dict(battle.get("player"))+ return {+ "type": "decision",+ "decision": "hand_select",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "mode": hand_select.get("mode"),+ "prompt": hand_select.get("prompt"),+ "cards": _copy_list(hand_select.get("cards")),+ "selected_cards": _copy_list(hand_select.get("selected_cards")),+ "can_confirm": hand_select.get("can_confirm", False),+ "player": player,+ "battle": battle,+ "hand_select": hand_select,+ }+++def _normalize_card_reward(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ reward = _copy_dict(raw_state.get("card_reward"))+ return {+ "type": "decision",+ "decision": "card_reward",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "cards": _copy_list(reward.get("cards")),+ "can_skip": reward.get("can_skip", False),+ "player": _copy_dict(reward.get("player")),+ "card_reward": reward,+ }+++def _normalize_combat_rewards(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ rewards = _copy_dict(raw_state.get("rewards"))+ return {+ "type": "decision",+ "decision": "combat_rewards",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "items": _copy_list(rewards.get("items")),+ "can_proceed": rewards.get("can_proceed", False),+ "player": _copy_dict(rewards.get("player")),+ "rewards": rewards,+ }+++def _normalize_map(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ map_state = _copy_dict(raw_state.get("map"))+ return {+ "type": "decision",+ "decision": "map_select",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "choices": _copy_list(map_state.get("next_options")),+ "player": _copy_dict(map_state.get("player")),+ "current_position": _copy_dict(map_state.get("current_position")),+ "visited": _copy_list(map_state.get("visited")),+ "nodes": _copy_list(map_state.get("nodes")),+ "boss": _copy_dict(map_state.get("boss")),+ "map": map_state,+ }+++def _normalize_event(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ event = _copy_dict(raw_state.get("event"))+ return {+ "type": "decision",+ "decision": "event_choice",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "event_name": event.get("event_name"),+ "event_id": event.get("event_id"),+ "description": event.get("body"),+ "options": _copy_list(event.get("options")),+ "player": _copy_dict(event.get("player")),+ "in_dialogue": event.get("in_dialogue", False),+ "is_ancient": event.get("is_ancient", False),+ "event": event,+ }+++def _normalize_rest_site(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ rest = _copy_dict(raw_state.get("rest_site"))+ return {+ "type": "decision",+ "decision": "rest_site",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "options": _copy_list(rest.get("options")),+ "player": _copy_dict(rest.get("player")),+ "can_proceed": rest.get("can_proceed", False),+ "rest_site": rest,+ }+++def _normalize_shop(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ shop = _copy_dict(raw_state.get("shop"))+ items = _copy_list(shop.get("items"))+ return {+ "type": "decision",+ "decision": "shop",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "items": items,+ "cards": [item for item in items if item.get("category") == "card"],+ "relics": [item for item in items if item.get("category") == "relic"],+ "potions": [item for item in items if item.get("category") == "potion"],+ "card_removal": next((item for item in items if item.get("category") == "card_removal"), None),+ "player": _copy_dict(shop.get("player")),+ "can_proceed": shop.get("can_proceed", False),+ "shop": shop,+ }+++def _normalize_card_select(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ card_select = _copy_dict(raw_state.get("card_select"))+ return {+ "type": "decision",+ "decision": "card_select",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "screen_type": card_select.get("screen_type"),+ "prompt": card_select.get("prompt"),+ "cards": _copy_list(card_select.get("cards")),+ "player": _copy_dict(card_select.get("player")),+ "preview_showing": card_select.get("preview_showing", False),+ "can_skip": card_select.get("can_skip", False),+ "can_confirm": card_select.get("can_confirm", False),+ "can_cancel": card_select.get("can_cancel", False),+ "card_select": card_select,+ }+++def _normalize_relic_select(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ relic_select = _copy_dict(raw_state.get("relic_select"))+ return {+ "type": "decision",+ "decision": "relic_select",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "prompt": relic_select.get("prompt"),+ "relics": _copy_list(relic_select.get("relics")),+ "player": _copy_dict(relic_select.get("player")),+ "can_skip": relic_select.get("can_skip", False),+ "relic_select": relic_select,+ }+++def _normalize_treasure(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ treasure = _copy_dict(raw_state.get("treasure"))+ return {+ "type": "decision",+ "decision": "treasure",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "relics": _copy_list(treasure.get("relics")),+ "player": _copy_dict(treasure.get("player")),+ "can_proceed": treasure.get("can_proceed", False),+ "message": treasure.get("message"),+ "treasure": treasure,+ }+++def _normalize_game_over(raw_state: JsonDict, context: JsonDict) -> JsonDict:+ game_over = _copy_dict(raw_state.get("game_over"))+ return {+ "type": "decision",+ "decision": "game_over",+ "context": context,+ "run": _copy_dict(raw_state.get("run")),+ "player": _copy_dict(game_over.get("player")),+ "screen_type": game_over.get("screen_type"),+ "can_return_to_main_menu": game_over.get("can_return_to_main_menu", False),+ "can_continue": game_over.get("can_continue", False),+ "can_view_run": game_over.get("can_view_run", False),+ "options": _copy_list(game_over.get("options")),+ "game_over": game_over,+ }+++def _copy_dict(value: Any) -> JsonDict:+ return dict(value) if isinstance(value, dict) else {}+++def _copy_list(value: Any) -> list[Any]:+ return list(value) if isinstance(value, list) else []diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/types.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/types.pynew file mode 100644index 000000000..23512f86f--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/core/types.py@@ -0,0 +1,14 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any++JsonDict = dict[str, Any]+++@dataclass(slots=True)+class PlannedAction:+ action: str+ payload: JsonDict+ reason: str+diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/skills/SKILL.md b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/skills/SKILL.mdnew file mode 100644index 000000000..b675a727b--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/skills/SKILL.md@@ -0,0 +1,191 @@+---+name: >-+ cli-anything-sts2+description: >-+ Command-line interface for Slay the Spire 2 - Control the real game through a local bridge mod HTTP API. Reads normalized game state and sends action commands for combat, navigation, rewards, and menu management.+---++# cli-anything-slay-the-spire-ii++A stateful command-line interface for controlling the real Slay the Spire 2+game through the local `STS2_Bridge` mod. The CLI reads normalized game state+and sends action commands via a local HTTP API at `localhost:15526`.++## Installation++This CLI requires a bridge mod that runs inside the game process. Both the CLI+and the bridge are distributed from the same repository:++```+https://github.com/HKUDS/CLI-Anything+```++### 1. Install the CLI++```bash+git clone https://github.com/HKUDS/CLI-Anything.git+cd CLI-Anything/slay_the_spire_ii/agent-harness+pip install -e .+```++### 2. Build and install the bridge mod++The bridge mod is a `.NET 9` plugin that must be compiled and installed into+the game directory. Full instructions are in the repository README, but the+short version is:++```bash+cd CLI-Anything/slay_the_spire_ii/bridge/plugin+./build.sh+cd ../install+./install_bridge.sh+```++If the build script cannot auto-detect the game data directory, set+`STS2_GAME_DATA_DIR` explicitly:++```bash+STS2_GAME_DATA_DIR="/path/to/data_sts2" ./build.sh+```++### 3. Enable the mod and verify++Launch Slay the Spire 2 via Steam, enable the `STS2_Bridge` mod in the mod+manager, then verify the connection:++```bash+cli-anything-sts2 state+```++If this returns JSON, the CLI and bridge are connected.++**Prerequisites:**+- Python 3.10++- Slay the Spire 2 (Steam) with `STS2_Bridge` mod enabled+- `.NET 9 SDK` (only needed to build the bridge mod)++## Usage++### Basic Commands++```bash+# Read normalized game state (always start here)+cli-anything-sts2 state++# Start interactive REPL mode+cli-anything-sts2 repl++# Show all available commands+cli-anything-sts2 --help+```++## Command Groups++### State Inspection++| Command | Description |+|---------|-------------|+| `state` | Normalized state with `decision` field |+| `raw-state` | Raw bridge JSON |++### Main Menu++| Command | Description |+|---------|-------------|+| `continue-game` | Continue a saved run |+| `start-game --character IRONCLAD --ascension 0` | Start a new run |+| `abandon-game` | Abandon the current save |+| `return-to-main-menu` | Return to menu from any screen |++Characters: `IRONCLAD`, `SILENT`, `DEFECT`, `NECROBINDER`, `REGENT`++### Combat++| Command | Description |+|---------|-------------|+| `play-card <index> [--target <enemy_id>]` | Play a card from hand |+| `use-potion <slot> [--target <enemy_id>]` | Use a potion |+| `end-turn` | End the current turn |++### Map & Room Flow++| Command | Description |+|---------|-------------|+| `choose-map <index>` | Select a map node |+| `proceed` | Leave the current room |++### Rewards++| Command | Description |+|---------|-------------|+| `claim-reward <index>` | Claim a combat reward |+| `pick-card-reward <index>` | Pick a card reward |+| `skip-card-reward` | Skip the card reward |+| `claim-treasure-relic <index>` | Claim a treasure relic |+| `select-relic <index>` | Select a relic |+| `skip-relic-selection` | Skip relic selection |++### Events & Rest Sites++| Command | Description |+|---------|-------------|+| `event <index>` | Choose an event option |+| `advance-dialogue` | Advance dialogue-only events |+| `rest <index>` | Choose a campfire action |++### Shop++| Command | Description |+|---------|-------------|+| `shop-buy <index>` | Buy from the shop |++### Card/Relic Selection Overlays++| Command | Description |+|---------|-------------|+| `select-card <index>` | Select a card in overlay |+| `confirm-selection` | Confirm the current selection |+| `cancel-selection` | Cancel the current selection |+| `combat-select-card <index>` | Select a card during combat overlay |+| `combat-confirm-selection` | Confirm combat card selection |++### Raw Action++| Command | Description |+|---------|-------------|+| `action <name> --kv key=value` | Send a raw bridge action |++## Decision States++The `state` command returns JSON with a `decision` field indicating the current+game screen. Route your next command based on this value:++| Decision | Meaning | Typical Next Commands |+|----------|---------|----------------------|+| `menu` | Main menu | `continue-game`, `start-game` |+| `combat_play` | In combat, your turn | `play-card`, `use-potion`, `end-turn` |+| `hand_select` | Card selection overlay | `combat-select-card`, `combat-confirm-selection` |+| `map_select` | Map node selection | `choose-map` |+| `game_over` | Run ended | `return-to-main-menu` |+| `combat_rewards` | Post-combat rewards | `claim-reward`, `proceed` |+| `card_reward` | Card reward pick | `pick-card-reward`, `skip-card-reward` |+| `event_choice` | Event screen | `event`, `advance-dialogue` |+| `rest_site` | Campfire | `rest` |+| `shop` | Shop screen | `shop-buy`, `proceed` |+| `card_select` | Card selection screen | `select-card`, `confirm-selection` |+| `relic_select` | Relic selection | `select-relic`, `skip-relic-selection` |+| `treasure` | Treasure room | `claim-treasure-relic`, `proceed` |++## Configuration++| Option | Default | Description |+|--------|---------|-------------|+| `--base-url` | `http://localhost:15526` | Bridge API URL |+| `--timeout` | `10.0` | HTTP timeout in seconds |++## For AI Agents++1. **Always read `state` first** to get the `decision` field+2. **Re-read state after each action** - indices and energy change during combat+3. **Check return codes** - 0 for success, non-zero for errors+4. **Parse stdout** for JSON outputdiff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/slay_the_spire_ii_cli.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/slay_the_spire_ii_cli.pynew file mode 100644index 000000000..62b1098cd--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/slay_the_spire_ii_cli.py@@ -0,0 +1,250 @@+from __future__ import annotations++import argparse+import json+import shlex+import sys++from .core import action_adapter as actions+from .utils.sts2_backend import ApiError, Sts2RawClient+from .core.state_adapter import normalize_state+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ prog="sts2",+ description="CLI adapter for controlling the real STS2 game via the local bridge plugin.",+ )+ parser.add_argument("--base-url", default="http://localhost:15526", help="Local bridge API base URL")+ parser.add_argument("--timeout", type=float, default=10.0, help="HTTP timeout in seconds")++ sub = parser.add_subparsers(dest="command", required=True)++ sub.add_parser("raw-state", help="Print the raw bridge-plugin JSON state")+ sub.add_parser("state", help="Print the normalized CLI-style state")+ sub.add_parser("continue-game", help="Continue a saved run from the main menu")+ sub.add_parser("abandon-game", help="Abandon the saved run from the main menu")+ sub.add_parser("return-to-main-menu", help="Return to the main menu from an active run")++ p = sub.add_parser("start-game", help="Start a new singleplayer run from the main menu")+ p.add_argument("--character", default="IRONCLAD")+ p.add_argument("--ascension", type=int, default=0)++ p = sub.add_parser("action", help="Send a raw action by name")+ p.add_argument("name", help="Raw bridge-plugin action name")+ p.add_argument("--kv", action="append", default=[], help="Extra payload in key=value form")++ p = sub.add_parser("play-card", help="Play a card by hand index")+ p.add_argument("card_index", type=int)+ p.add_argument("--target")++ p = sub.add_parser("use-potion", help="Use a potion by slot index")+ p.add_argument("slot", type=int)+ p.add_argument("--target")++ sub.add_parser("end-turn", help="End turn")++ p = sub.add_parser("choose-map", help="Choose a map node by normalized index")+ p.add_argument("index", type=int)++ p = sub.add_parser("claim-reward", help="Claim a combat reward by index")+ p.add_argument("index", type=int)++ p = sub.add_parser("pick-card-reward", help="Pick a card reward by index")+ p.add_argument("index", type=int)++ sub.add_parser("skip-card-reward", help="Skip a card reward")+ sub.add_parser("proceed", help="Proceed/leave current room when supported")++ p = sub.add_parser("event", help="Choose an event option by index")+ p.add_argument("index", type=int)+ sub.add_parser("advance-dialogue", help="Advance ancient event dialogue")++ p = sub.add_parser("rest", help="Choose a rest site option by index")+ p.add_argument("index", type=int)++ p = sub.add_parser("shop-buy", help="Purchase a shop item by raw item index")+ p.add_argument("index", type=int)++ p = sub.add_parser("select-card", help="Select a card in an overlay by index")+ p.add_argument("index", type=int)+ sub.add_parser("confirm-selection", help="Confirm the current card selection")+ sub.add_parser("cancel-selection", help="Cancel/skip the current card selection")++ p = sub.add_parser("combat-select-card", help="Select a combat hand card during hand_select")+ p.add_argument("card_index", type=int)+ sub.add_parser("combat-confirm-selection", help="Confirm an in-combat card selection")++ p = sub.add_parser("select-relic", help="Select a relic by index")+ p.add_argument("index", type=int)+ sub.add_parser("skip-relic-selection", help="Skip relic selection")++ p = sub.add_parser("claim-treasure-relic", help="Claim a treasure room relic by index")+ p.add_argument("index", type=int)++ sub.add_parser("repl", help="Start an interactive sts2 shell")++ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ client = Sts2RawClient(base_url=args.base_url, timeout=args.timeout)++ try:+ if args.command == "raw-state":+ return _print_json(client.get_state(format="json"))++ if args.command == "state":+ raw = client.get_state(format="json")+ return _print_json(normalize_state(raw))++ if args.command == "continue-game":+ return _post_payload(client, actions.continue_game())++ if args.command == "abandon-game":+ return _post_payload(client, actions.abandon_game())++ if args.command == "return-to-main-menu":+ return _post_payload(client, actions.return_to_main_menu())++ if args.command == "start-game":+ return _post_payload(client, actions.start_new_game(args.character, args.ascension))++ if args.command == "action":+ payload = _parse_kv_pairs(args.kv)+ return _print_json(client.post_action(args.name, **payload))++ if args.command == "play-card":+ return _post_payload(client, actions.play_card(args.card_index, target=args.target))++ if args.command == "use-potion":+ return _post_payload(client, actions.use_potion(args.slot, target=args.target))++ if args.command == "end-turn":+ return _post_payload(client, actions.end_turn())++ if args.command == "choose-map":+ return _post_payload(client, actions.choose_map_node(args.index))++ if args.command == "claim-reward":+ return _post_payload(client, actions.claim_reward(args.index))++ if args.command == "pick-card-reward":+ return _post_payload(client, actions.select_card_reward(args.index))++ if args.command == "skip-card-reward":+ return _post_payload(client, actions.skip_card_reward())++ if args.command == "proceed":+ return _post_payload(client, actions.proceed())++ if args.command == "event":+ return _post_payload(client, actions.choose_event_option(args.index))++ if args.command == "advance-dialogue":+ return _post_payload(client, actions.advance_dialogue())++ if args.command == "rest":+ return _post_payload(client, actions.choose_rest_option(args.index))++ if args.command == "shop-buy":+ return _post_payload(client, actions.shop_purchase(args.index))++ if args.command == "select-card":+ return _post_payload(client, actions.select_card(args.index))++ if args.command == "confirm-selection":+ return _post_payload(client, actions.confirm_selection())++ if args.command == "cancel-selection":+ return _post_payload(client, actions.cancel_selection())++ if args.command == "combat-select-card":+ return _post_payload(client, actions.combat_select_card(args.card_index))++ if args.command == "combat-confirm-selection":+ return _post_payload(client, actions.combat_confirm_selection())++ if args.command == "select-relic":+ return _post_payload(client, actions.select_relic(args.index))++ if args.command == "skip-relic-selection":+ return _post_payload(client, actions.skip_relic_selection())++ if args.command == "claim-treasure-relic":+ return _post_payload(client, actions.claim_treasure_relic(args.index))++ if args.command == "repl":+ return _run_repl(args.base_url, args.timeout)++ parser.error(f"Unhandled command: {args.command}")+ return 2+ except (ApiError, RuntimeError, ValueError) as exc:+ print(str(exc), file=sys.stderr)+ return 1+++def _post_payload(client: Sts2RawClient, payload: dict[str, object]) -> int:+ action = str(payload.pop("action"))+ return _print_json(client.post_action(action, **payload))+++def _parse_kv_pairs(entries: list[str]) -> dict[str, object]:+ result: dict[str, object] = {}+ for entry in entries:+ if "=" not in entry:+ raise ValueError(f"Expected key=value, got: {entry}")+ key, raw_value = entry.split("=", 1)+ result[key] = _coerce_value(raw_value)+ return result+++def _coerce_value(raw: str) -> object:+ if raw.isdigit() or (raw.startswith("-") and raw[1:].isdigit()):+ return int(raw)+ if raw.lower() == "true":+ return True+ if raw.lower() == "false":+ return False+ return raw+++def _print_json(value: object) -> int:+ json.dump(value, sys.stdout, ensure_ascii=False, indent=2)+ sys.stdout.write("\n")+ return 0+++def _run_repl(base_url: str, timeout: float) -> int:+ print("STS2CLI REPL")+ print("Type a normal subcommand such as `state` or `play-card 0 --target NIBBIT_0`.")+ print("Type `help` to show command help. Type `exit` or `quit` to leave.")++ while True:+ try:+ line = input("sts2> ").strip()+ except EOFError:+ sys.stdout.write("\n")+ return 0+ except KeyboardInterrupt:+ sys.stdout.write("\n")+ return 0++ if not line:+ continue+ if line in {"exit", "quit"}:+ return 0+ if line == "help":+ build_parser().print_help()+ continue++ argv = ["--base-url", base_url, "--timeout", str(timeout), *shlex.split(line)]+ code = main(argv)+ if code != 0:+ print(f"[exit {code}]", file=sys.stderr)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/__init__.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/__init__.pynew file mode 100644index 000000000..0d0dcef14--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/__init__.py@@ -0,0 +1 @@+"""Utility modules for Slay the Spire 2 CLI."""diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/repl_skin.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/repl_skin.pynew file mode 100644index 000000000..c7312348a--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/repl_skin.py@@ -0,0 +1,521 @@+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.++Copy this file into your CLI package at:+ cli_anything/<software>/utils/repl_skin.py++Usage:+ from cli_anything.<software>.utils.repl_skin import ReplSkin++ skin = ReplSkin("shotcut", version="1.0.0")+ skin.print_banner() # auto-detects skills/SKILL.md inside the package+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)+ skin.success("Project saved")+ skin.error("File not found")+ skin.warning("Unsaved changes")+ skin.info("Processing 24 clips...")+ skin.status("Track 1", "3 clips, 00:02:30")+ skin.table(headers, rows)+ skin.print_goodbye()+"""++import os+import sys++# ── ANSI color codes (no external deps for core styling) ──────────────++_RESET = "\033[0m"+_BOLD = "\033[1m"+_DIM = "\033[2m"+_ITALIC = "\033[3m"+_UNDERLINE = "\033[4m"++# Brand colors+_CYAN = "\033[38;5;80m" # cli-anything brand cyan+_CYAN_BG = "\033[48;5;80m"+_WHITE = "\033[97m"+_GRAY = "\033[38;5;245m"+_DARK_GRAY = "\033[38;5;240m"+_LIGHT_GRAY = "\033[38;5;250m"++# Software accent colors — each software gets a unique accent+_ACCENT_COLORS = {+ "gimp": "\033[38;5;214m", # warm orange+ "blender": "\033[38;5;208m", # deep orange+ "inkscape": "\033[38;5;39m", # bright blue+ "audacity": "\033[38;5;33m", # navy blue+ "libreoffice": "\033[38;5;40m", # green+ "obs_studio": "\033[38;5;55m", # purple+ "kdenlive": "\033[38;5;69m", # slate blue+ "shotcut": "\033[38;5;35m", # teal green+}+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue++# Status colors+_GREEN = "\033[38;5;78m"+_YELLOW = "\033[38;5;220m"+_RED = "\033[38;5;196m"+_BLUE = "\033[38;5;75m"+_MAGENTA = "\033[38;5;176m"++# ── Brand icon ────────────────────────────────────────────────────────++# The cli-anything icon: a small colored diamond/chevron mark+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"+_ICON_SMALL = f"{_CYAN}▸{_RESET}"++# ── Box drawing characters ────────────────────────────────────────────++_H_LINE = "─"+_V_LINE = "│"+_TL = "╭"+_TR = "╮"+_BL = "╰"+_BR = "╯"+_T_DOWN = "┬"+_T_UP = "┴"+_T_RIGHT = "├"+_T_LEFT = "┤"+_CROSS = "┼"+++def _strip_ansi(text: str) -> str:+ """Remove ANSI escape codes for length calculation."""+ import re+ return re.sub(r"\033\[[^m]*m", "", text)+++def _visible_len(text: str) -> int:+ """Get visible length of text (excluding ANSI codes)."""+ return len(_strip_ansi(text))+++class ReplSkin:+ """Unified REPL skin for cli-anything CLIs.++ Provides consistent branding, prompts, and message formatting+ across all CLI harnesses built with the cli-anything methodology.+ """++ def __init__(self, software: str, version: str = "1.0.0",+ history_file: str | None = None, skill_path: str | None = None):+ """Initialize the REPL skin.++ Args:+ software: Software name (e.g., "gimp", "shotcut", "blender").+ version: CLI version string.+ history_file: Path for persistent command history.+ Defaults to ~/.cli-anything-<software>/history+ skill_path: Path to the SKILL.md file for agent discovery.+ Auto-detected from the package's skills/ directory if not provided.+ Displayed in banner for AI agents to know where to read skill info.+ """+ self.software = software.lower().replace("-", "_")+ self.display_name = software.replace("_", " ").title()+ self.version = version++ # Auto-detect skill path from package layout:+ # cli_anything/<software>/utils/repl_skin.py (this file)+ # cli_anything/<software>/skills/SKILL.md (target)+ if skill_path is None:+ from pathlib import Path+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"+ if _auto.is_file():+ skill_path = str(_auto)+ self.skill_path = skill_path+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)++ # History file+ if history_file is None:+ from pathlib import Path+ hist_dir = Path.home() / f".cli-anything-{self.software}"+ hist_dir.mkdir(parents=True, exist_ok=True)+ self.history_file = str(hist_dir / "history")+ else:+ self.history_file = history_file++ # Detect terminal capabilities+ self._color = self._detect_color_support()++ def _detect_color_support(self) -> bool:+ """Check if terminal supports color."""+ if os.environ.get("NO_COLOR"):+ return False+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):+ return False+ if not hasattr(sys.stdout, "isatty"):+ return False+ return sys.stdout.isatty()++ def _c(self, code: str, text: str) -> str:+ """Apply color code if colors are supported."""+ if not self._color:+ return text+ return f"{code}{text}{_RESET}"++ # ── Banner ────────────────────────────────────────────────────────++ def print_banner(self):+ """Print the startup banner with branding."""+ inner = 54++ def _box_line(content: str) -> str:+ """Wrap content in box drawing, padding to inner width."""+ pad = inner - _visible_len(content)+ vl = self._c(_DARK_GRAY, _V_LINE)+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"++ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")++ # Title: ◆ cli-anything · Shotcut+ icon = self._c(_CYAN + _BOLD, "◆")+ brand = self._c(_CYAN + _BOLD, "cli-anything")+ dot = self._c(_DARK_GRAY, "·")+ name = self._c(self.accent + _BOLD, self.display_name)+ title = f" {icon} {brand} {dot} {name}"++ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"+ empty = ""++ # Skill path for agent discovery+ skill_line = None+ if self.skill_path:+ skill_icon = self._c(_MAGENTA, "◇")+ skill_label = self._c(_DARK_GRAY, " Skill:")+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"++ print(top)+ print(_box_line(title))+ print(_box_line(ver))+ if skill_line:+ print(_box_line(skill_line))+ print(_box_line(empty))+ print(_box_line(tip))+ print(bot)+ print()++ # ── Prompt ────────────────────────────────────────────────────────++ def prompt(self, project_name: str = "", modified: bool = False,+ context: str = "") -> str:+ """Build a styled prompt string for prompt_toolkit or input().++ Args:+ project_name: Current project name (empty if none open).+ modified: Whether the project has unsaved changes.+ context: Optional extra context to show in prompt.++ Returns:+ Formatted prompt string.+ """+ parts = []++ # Icon+ if self._color:+ parts.append(f"{_CYAN}◆{_RESET} ")+ else:+ parts.append("> ")++ # Software name+ parts.append(self._c(self.accent + _BOLD, self.software))++ # Project context+ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ parts.append(f" {self._c(_DARK_GRAY, '[')}")+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))+ parts.append(self._c(_DARK_GRAY, ']'))++ parts.append(self._c(_GRAY, " ❯ "))++ return "".join(parts)++ def prompt_tokens(self, project_name: str = "", modified: bool = False,+ context: str = ""):+ """Build prompt_toolkit formatted text tokens for the prompt.++ Use with prompt_toolkit's FormattedText for proper ANSI handling.++ Returns:+ list of (style, text) tuples for prompt_toolkit.+ """+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")+ tokens = []++ tokens.append(("class:icon", "◆ "))+ tokens.append(("class:software", self.software))++ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ tokens.append(("class:bracket", " ["))+ tokens.append(("class:context", f"{ctx}{mod}"))+ tokens.append(("class:bracket", "]"))++ tokens.append(("class:arrow", " ❯ "))++ return tokens++ def get_prompt_style(self):+ """Get a prompt_toolkit Style object matching the skin.++ Returns:+ prompt_toolkit.styles.Style+ """+ try:+ from prompt_toolkit.styles import Style+ except ImportError:+ return None++ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")++ return Style.from_dict({+ "icon": "#5fdfdf bold", # cyan brand color+ "software": f"{accent_hex} bold",+ "bracket": "#585858",+ "context": "#bcbcbc",+ "arrow": "#808080",+ # Completion menu+ "completion-menu.completion": "bg:#303030 #bcbcbc",+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",+ "completion-menu.meta.completion": "bg:#303030 #808080",+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",+ # Auto-suggest+ "auto-suggest": "#585858",+ # Bottom toolbar+ "bottom-toolbar": "bg:#1c1c1c #808080",+ "bottom-toolbar.text": "#808080",+ })++ # ── Messages ──────────────────────────────────────────────────────++ def success(self, message: str):+ """Print a success message with green checkmark."""+ icon = self._c(_GREEN + _BOLD, "✓")+ print(f" {icon} {self._c(_GREEN, message)}")++ def error(self, message: str):+ """Print an error message with red cross."""+ icon = self._c(_RED + _BOLD, "✗")+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)++ def warning(self, message: str):+ """Print a warning message with yellow triangle."""+ icon = self._c(_YELLOW + _BOLD, "⚠")+ print(f" {icon} {self._c(_YELLOW, message)}")++ def info(self, message: str):+ """Print an info message with blue dot."""+ icon = self._c(_BLUE, "●")+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")++ def hint(self, message: str):+ """Print a subtle hint message."""+ print(f" {self._c(_DARK_GRAY, message)}")++ def section(self, title: str):+ """Print a section header."""+ print()+ print(f" {self._c(self.accent + _BOLD, title)}")+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")++ # ── Status display ────────────────────────────────────────────────++ def status(self, label: str, value: str):+ """Print a key-value status line."""+ lbl = self._c(_GRAY, f" {label}:")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def status_block(self, items: dict[str, str], title: str = ""):+ """Print a block of status key-value pairs.++ Args:+ items: Dict of label -> value pairs.+ title: Optional title for the block.+ """+ if title:+ self.section(title)++ max_key = max(len(k) for k in items) if items else 0+ for label, value in items.items():+ lbl = self._c(_GRAY, f" {label:<{max_key}}")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def progress(self, current: int, total: int, label: str = ""):+ """Print a simple progress indicator.++ Args:+ current: Current step number.+ total: Total number of steps.+ label: Optional label for the progress.+ """+ pct = int(current / total * 100) if total > 0 else 0+ bar_width = 20+ filled = int(bar_width * current / total) if total > 0 else 0+ bar = "█" * filled + "░" * (bar_width - filled)+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"+ if label:+ text += f" {self._c(_LIGHT_GRAY, label)}"+ print(text)++ # ── Table display ─────────────────────────────────────────────────++ def table(self, headers: list[str], rows: list[list[str]],+ max_col_width: int = 40):+ """Print a formatted table with box-drawing characters.++ Args:+ headers: Column header strings.+ rows: List of rows, each a list of cell strings.+ max_col_width: Maximum column width before truncation.+ """+ if not headers:+ return++ # Calculate column widths+ col_widths = [min(len(h), max_col_width) for h in headers]+ for row in rows:+ for i, cell in enumerate(row):+ if i < len(col_widths):+ col_widths[i] = min(+ max(col_widths[i], len(str(cell))), max_col_width+ )++ def pad(text: str, width: int) -> str:+ t = str(text)[:width]+ return t + " " * (width - len(t))++ # Header+ header_cells = [+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))+ for i, h in enumerate(headers)+ ]+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ header_line = f" {sep.join(header_cells)}"+ print(header_line)++ # Separator+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")+ print(sep_line)++ # Rows+ for row in rows:+ cells = []+ for i, cell in enumerate(row):+ if i < len(col_widths):+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ print(f" {row_sep.join(cells)}")++ # ── Help display ──────────────────────────────────────────────────++ def help(self, commands: dict[str, str]):+ """Print a formatted help listing.++ Args:+ commands: Dict of command -> description pairs.+ """+ self.section("Commands")+ max_cmd = max(len(c) for c in commands) if commands else 0+ for cmd, desc in commands.items():+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")+ desc_styled = self._c(_GRAY, f" {desc}")+ print(f"{cmd_styled}{desc_styled}")+ print()++ # ── Goodbye ───────────────────────────────────────────────────────++ def print_goodbye(self):+ """Print a styled goodbye message."""+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")++ # ── Prompt toolkit session factory ────────────────────────────────++ def create_prompt_session(self):+ """Create a prompt_toolkit PromptSession with skin styling.++ Returns:+ A configured PromptSession, or None if prompt_toolkit unavailable.+ """+ try:+ from prompt_toolkit import PromptSession+ from prompt_toolkit.history import FileHistory+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory+ from prompt_toolkit.formatted_text import FormattedText++ style = self.get_prompt_style()++ session = PromptSession(+ history=FileHistory(self.history_file),+ auto_suggest=AutoSuggestFromHistory(),+ style=style,+ enable_history_search=True,+ )+ return session+ except ImportError:+ return None++ def get_input(self, pt_session, project_name: str = "",+ modified: bool = False, context: str = "") -> str:+ """Get input from user using prompt_toolkit or fallback.++ Args:+ pt_session: A prompt_toolkit PromptSession (or None).+ project_name: Current project name.+ modified: Whether project has unsaved changes.+ context: Optional context string.++ Returns:+ User input string (stripped).+ """+ if pt_session is not None:+ from prompt_toolkit.formatted_text import FormattedText+ tokens = self.prompt_tokens(project_name, modified, context)+ return pt_session.prompt(FormattedText(tokens)).strip()+ else:+ raw_prompt = self.prompt(project_name, modified, context)+ return input(raw_prompt).strip()++ # ── Toolbar builder ───────────────────────────────────────────────++ def bottom_toolbar(self, items: dict[str, str]):+ """Create a bottom toolbar callback for prompt_toolkit.++ Args:+ items: Dict of label -> value pairs to show in toolbar.++ Returns:+ A callable that returns FormattedText for the toolbar.+ """+ def toolbar():+ from prompt_toolkit.formatted_text import FormattedText+ parts = []+ for i, (k, v) in enumerate(items.items()):+ if i > 0:+ parts.append(("class:bottom-toolbar.text", " │ "))+ parts.append(("class:bottom-toolbar.text", f" {k}: "))+ parts.append(("class:bottom-toolbar", v))+ return FormattedText(parts)+ return toolbar+++# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────++_ANSI_256_TO_HEX = {+ "\033[38;5;33m": "#0087ff", # audacity navy blue+ "\033[38;5;35m": "#00af5f", # shotcut teal+ "\033[38;5;39m": "#00afff", # inkscape bright blue+ "\033[38;5;40m": "#00d700", # libreoffice green+ "\033[38;5;55m": "#5f00af", # obs purple+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue+ "\033[38;5;75m": "#5fafff", # default sky blue+ "\033[38;5;80m": "#5fd7d7", # brand cyan+ "\033[38;5;208m": "#ff8700", # blender deep orange+ "\033[38;5;214m": "#ffaf00", # gimp warm orange+}diff --git a/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/sts2_backend.py b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/sts2_backend.pynew file mode 100644index 000000000..b79768e9e--- /dev/null+++ b/slay_the_spire_ii/agent-harness/cli_anything/slay_the_spire_ii/utils/sts2_backend.py@@ -0,0 +1,61 @@+from __future__ import annotations++import json+import urllib.error+import urllib.parse+import urllib.request+from typing import Any++from ..core.types import JsonDict+++class ApiError(RuntimeError):+ """Raised when the local game bridge returns an error."""+++class Sts2RawClient:+ def __init__(self, base_url: str = "http://localhost:15526", timeout: float = 10.0):+ self.base_url = base_url.rstrip("/")+ self.timeout = timeout++ @property+ def singleplayer_url(self) -> str:+ return f"{self.base_url}/api/v1/singleplayer"++ def get_state(self, *, format: str = "json") -> JsonDict | str:+ query = urllib.parse.urlencode({"format": format})+ url = f"{self.singleplayer_url}?{query}"+ return self._request_json("GET", url) if format == "json" else self._request_text("GET", url)++ def post_action(self, action: str, **payload: Any) -> JsonDict:+ body: JsonDict = {"action": action, **payload}+ return self._request_json("POST", self.singleplayer_url, body)++ def _request_text(self, method: str, url: str, body: JsonDict | None = None) -> str:+ req = urllib.request.Request(url, method=method)+ if body is not None:+ data = json.dumps(body).encode("utf-8")+ req.add_header("Content-Type", "application/json")+ else:+ data = None++ try:+ with urllib.request.urlopen(req, data=data, timeout=self.timeout) as resp:+ return resp.read().decode("utf-8")+ except urllib.error.HTTPError as exc:+ text = exc.read().decode("utf-8", errors="replace")+ raise ApiError(f"HTTP {exc.code}: {text}") from exc+ except urllib.error.URLError as exc:+ raise ApiError(+ "Cannot connect to the game bridge API. Is the game running with the bridge mod enabled?"+ ) from exc++ def _request_json(self, method: str, url: str, body: JsonDict | None = None) -> JsonDict:+ text = self._request_text(method, url, body)+ try:+ data = json.loads(text)+ except json.JSONDecodeError as exc:+ raise ApiError(f"Expected JSON response, got: {text[:200]}") from exc+ if not isinstance(data, dict):+ raise ApiError(f"Expected object response, got: {type(data).__name__}")+ return datadiff --git a/slay_the_spire_ii/agent-harness/setup.py b/slay_the_spire_ii/agent-harness/setup.pynew file mode 100644index 000000000..0e7cee475--- /dev/null+++ b/slay_the_spire_ii/agent-harness/setup.py@@ -0,0 +1,52 @@+#!/usr/bin/env python3+"""+setup.py for cli-anything-slay-the-spire-ii++Install with: pip install -e .+Or publish to PyPI: python -m build && twine upload dist/*+"""++from setuptools import setup, find_namespace_packages++with open("cli_anything/slay_the_spire_ii/README.md", "r", encoding="utf-8") as fh:+ long_description = fh.read()++setup(+ name="cli-anything-slay-the-spire-ii",+ version="1.0.0",+ author="cli-anything contributors",+ author_email="",+ description="CLI harness for Slay the Spire 2 - Control the real game via a local bridge mod. Requires: Slay the Spire 2 (Steam) with STS2_Bridge mod enabled",+ long_description=long_description,+ long_description_content_type="text/markdown",+ url="https://github.com/HKUDS/CLI-Anything",+ packages=find_namespace_packages(include=["cli_anything.*"]),+ classifiers=[+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "Topic :: Games/Entertainment",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ ],+ python_requires=">=3.10",+ install_requires=[],+ extras_require={+ "dev": [+ "pytest>=7.0.0",+ "pytest-cov>=4.0.0",+ ],+ },+ entry_points={+ "console_scripts": [+ "cli-anything-sts2=cli_anything.slay_the_spire_ii.slay_the_spire_ii_cli:main",+ ],+ },+ package_data={+ "cli_anything.slay_the_spire_ii": ["skills/*.md"],+ },+ include_package_data=True,+ zip_safe=False,+)