Gladiator-codes commited on
Commit
a59b710
·
verified ·
1 Parent(s): 03d77a9

Upload folder using huggingface_hub

Browse files
Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
2
+ FROM ${BASE_IMAGE} AS builder
3
+
4
+ WORKDIR /app
5
+ COPY . /app/env
6
+ WORKDIR /app/env
7
+
8
+ RUN if ! command -v uv >/dev/null 2>&1; then \
9
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
10
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
11
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
12
+ fi
13
+
14
+ RUN apt-get update && apt-get install -y --no-install-recommends \
15
+ git \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ RUN --mount=type=cache,target=/root/.cache/uv \
19
+ if [ -f uv.lock ]; then \
20
+ uv sync --frozen --no-install-project --no-editable; \
21
+ else \
22
+ uv sync --no-install-project --no-editable; \
23
+ fi
24
+
25
+ RUN --mount=type=cache,target=/root/.cache/uv \
26
+ if [ -f uv.lock ]; then \
27
+ uv sync --frozen --no-editable; \
28
+ else \
29
+ uv sync --no-editable; \
30
+ fi
31
+
32
+ FROM ${BASE_IMAGE}
33
+
34
+ WORKDIR /app
35
+ COPY --from=builder /app/env/.venv /app/.venv
36
+ COPY --from=builder /app/env /app/env
37
+
38
+ ENV PATH="/app/.venv/bin:$PATH"
39
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
40
+ ENV ENABLE_WEB_INTERFACE=true
41
+
42
+ # Must match Uvicorn / Space settings + README app_port (HF routes health checks here).
43
+ EXPOSE 7860
44
+
45
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port ${PORT:-7860}"]
README.md CHANGED
@@ -1,10 +1,173 @@
1
- ---
2
- title: Sinchan Env
3
- emoji: 📊
4
- colorFrom: indigo
5
- colorTo: purple
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ShinChan Life Simulator
3
+ colorFrom: yellow
4
+ colorTo: blue
5
+ sdk: docker
6
+ app_port: 7860
7
+ pinned: false
8
+ license: mit
9
+ short_description: Shin-chan OpenEnv RL with TRL GRPO training and Gradio UI.
10
+ base_path: /web
11
+ ---
12
+
13
+ # ShinChan Life Simulator
14
+
15
+ **OpenEnv**-based RL environment: an agent plays as Shin-chan through social / family / school dilemmas and learns to reduce harmful outcomes while staying in character. Training uses **Hugging Face TRL GRPO** with optional **QLoRA (4-bit + PEFT)** for low memory.
16
+
17
+ | Resource | Link |
18
+ |----------|------|
19
+ | **Hugging Face Space (cards)** | [https://huggingface.co/spaces/Gladiator-codes/sinchan-env](https://huggingface.co/spaces/Gladiator-codes/sinchan-env) |
20
+ | **Space runtime (Gradio + OpenEnv)** | Use the URL from your Space (see *Deployment*); pattern: `https://<org>-<name>.hf.space` (revision hosts may end with a hash, e.g. `...-a446abd.hf.space`). |
21
+ | **Colab (end-to-end training)** | [Open `training/ShinChan_GRPO_Training.ipynb` in Colab](https://colab.research.google.com/github/Sarthaks-24/sinchan_env/blob/main/training/ShinChan_GRPO_Training.ipynb) |
22
+ | **Repository** | [https://github.com/Sarthaks-24/sinchan_env](https://github.com/Sarthaks-24/sinchan_env) |
23
+ | **Mini blog (served on the Space)** | `https://<your-runtime-host>/blog.md` (same host as `/health` - e.g. `https://<...>.hf.space/blog.md` after deploy) |
24
+
25
+ > **No large model weights in git.** Upload checkpoints to a Hub model repo and link them here; this repo only stores scripts, small JSON/MD evidence, and small PNGs.
26
+
27
+ ---
28
+
29
+ ## 1. Problem motivation
30
+
31
+ Short-horizon social dilemmas have **conflicting incentives** (fun now vs trust tomorrow). A policy must trade off personality (dialogue) against outcomes (rewards, relationships). The environment makes those tradeoffs explicit and teaches an LLM to act through **tool calls** (`choose_action`).
32
+
33
+ ---
34
+
35
+ ## 2. Environment design
36
+
37
+ - **MCP / HTTP** via OpenEnv: tools `new_episode`, `get_scenario_info`, `get_relationships`, `choose_action`.
38
+ - **Episodes** sample scenarios with multiple steps; the UI shows narrative + legal actions.
39
+ - **Concurrency:** OpenEnv `create_app` with `max_concurrent` sessions (see `server/app.py`).
40
+
41
+ ---
42
+
43
+ ## 3. Reward function logic (summary)
44
+
45
+ Rewards are **dense, multi-term** and returned on each `choose_action` (e.g. responsibility, relationship alignment, in-character style). The exact weights live in `server/reward_engine.py` and are echoed as `reward_components` in the tool JSON.
46
+
47
+ ---
48
+
49
+ ## 4. Training setup
50
+
51
+ | Item | Choice |
52
+ |------|--------|
53
+ | **Stack** | **TRL** `GRPOTrainer` + OpenEnv `environment_factory` (remote or local) |
54
+ | **Model** | `Qwen/Qwen3-0.6B` (tool-friendly chat template; small enough for Colab) |
55
+ | **Memory** | Optional **`--use-qlora`**: 4-bit + PEFT LoRA (install `peft`, `bitsandbytes`; **GPU** required) |
56
+ | **Repro** | `run_metadata.json` + `metrics.jsonl` in each run directory; `seed` in `GRPOConfig` |
57
+
58
+ **Staged pipeline (modular, debuggable):**
59
+
60
+ | Stage | Script | Purpose |
61
+ |-------|--------|---------|
62
+ | 1 | `training/stage1_validate_env.py` | Reset, random policy, log transitions and rewards |
63
+ | 2 | `training/stage2_minimal_train.py` | 50-100-step-style sanity GRPO (delegates to `train_sinchan.py`) |
64
+ | 3 | `training/stage3_full_train.py` | Longer run -> `training/artifacts/run1` (default) |
65
+ | 4 | `training/stage4_evaluate.py` | Baselines (random vs rule) + report vs training logs |
66
+ | All | `training/run_pipeline.py` | Runs stages in order, then `plot_metrics.py` |
67
+
68
+ **Core trainer:** `training/train_sinchan.py` (shared by Colab and local).
69
+
70
+ **Install (dev + training):**
71
+
72
+ ```bash
73
+ pip install -e ".[training]"
74
+
75
+ # optional W&B: export WANDB_API_KEY=... (local PNGs are always written via plot_metrics)
76
+ ```
77
+
78
+ **Preflight the Space (HTTP, no WebSocket):**
79
+
80
+ ```bash
81
+ python training/preflight_space.py --base-url https://<your>.hf.space --retries 3
82
+ ```
83
+
84
+ ---
85
+
86
+ ## 5. Results (evidence: real training)
87
+
88
+ After a run, you should have:
89
+
90
+ - `training/artifacts/<run>/metrics.jsonl` - one JSON object per `on_log` (from `train_sinchan.py`)
91
+ - `training/artifacts/<run>/trainer_state.json` - TRL state (may include `log_history`)
92
+ - `training/artifacts/eval_summary.json` - from `training/evaluate_scenarios.py`
93
+ - **Plots** in `assets/` (generate; then commit the PNGs if required):
94
+
95
+ ```bash
96
+ python training/plot_metrics.py --run-dir training/artifacts/run1 --eval-summary training/artifacts/eval_summary.json --assets-dir assets
97
+ ```
98
+
99
+ | Plot | File |
100
+ |------|------|
101
+ | Reward curve | `assets/reward_curve_total.png` |
102
+ | Loss curve | `assets/loss_curve.png` |
103
+ | Baseline bar chart | `assets/baseline_comparison.png` |
104
+
105
+ ---
106
+
107
+ ## 6. Before vs after (how to read it)
108
+
109
+ | View | "Before / untrained" | "After / trained signal" |
110
+ |------|------------------------|---------------------------|
111
+ | **Env rollouts** | **Random** average reward in `eval_summary.json` | **Rule-based** average (informed baseline) in the same file |
112
+ | **RL optimization** | N/A | **Training reward** from `metrics.jsonl` / `log_history` (trend up vs random baseline) |
113
+
114
+ Per-scenario numbers change every episode sample; the **reported aggregates** in `eval_summary.json` and the **training curves** are the stable submission evidence.
115
+
116
+ | Scenario (example) | Before (random policy) | After (see evidence) |
117
+ |--------------------|------------------------|------------------------|
118
+ | Last Chocobi | *from `eval_summary.json` runs* | *training curve + last-K mean reward* |
119
+ | Homework Dilemma | ^ | ^ |
120
+ | Broken Window Trouble | ^ | ^ |
121
+ | Teacher in Tears | ^ | ^ |
122
+ | Candy from a Stranger | ^ | ^ |
123
+
124
+ Fill the numeric columns after you run `stage4_evaluate.py` and paste from `eval_summary` + your training summary.
125
+
126
+ ---
127
+
128
+ ## 7. Hugging Face Space / UI
129
+
130
+ - **OpenEnv:** `/web` (when `ENABLE_WEB_INTERFACE` is on), `/health` for probes.
131
+ - **Crayon static UI:** `/play` -> `/sinchan-ui/`.
132
+ - **Gradio (required simple UI):** **`/gradio`** - new episode, action, state, **reward** JSON.
133
+
134
+ **Deploy:** from repo root, use OpenEnv push (or your existing Docker Space):
135
+
136
+ ```bash
137
+ openenv push --repo-id Gladiator-codes/sinchan-env .
138
+ ```
139
+
140
+ **Blog on Space:** `GET /blog.md` (file `server/static/blog.md`).
141
+
142
+ ---
143
+
144
+ ## 8. Local quickstart
145
+
146
+ ```bash
147
+ pip install -e .
148
+ # PowerShell: $env:ENV_URL="http://127.0.0.1:8000"
149
+ uv run server
150
+ # Open: http://localhost:8000/web | http://localhost:8000/gradio | http://localhost:8000/blog.md
151
+ ```
152
+
153
+ ```bash
154
+ python -m pytest -q tests/test_smoke.py
155
+ ```
156
+
157
+ **Client example (hosted `https://`):** use `SinChanEnv(..., prefer_http_mcp=True)` (see `client.py`).
158
+
159
+ ---
160
+
161
+ ## 9. Unsloth
162
+
163
+ Primary instruction path is **TRL** (per hackathon). **Unsloth** is optional for fast LoRA on supported models; this repo is wired for **GRPO + OpenEnv** via TRL. If you add an Unsloth path, keep it in a *separate* script so TRL/Colab stays the default.
164
+
165
+ ---
166
+
167
+ ## 10. After you finish: next actions
168
+
169
+ Step-by-step post-submission checks are in **`WHAT_TO_DO_NEXT.md`** in the repository root (deployment, Colab, plots, Hub).
170
+
171
+ ---
172
+
173
+ *Commit small PNG/JSON only; do not store multi-GB checkpoints in git.*
RUNBOOK.md ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ShinChan Env Runbook (Friend Handoff)
2
+
3
+ This is the complete execution guide to run, deploy, train, evaluate, and submit the project.
4
+
5
+ ## 0) Prerequisites
6
+
7
+ - Windows with `py -3` available
8
+ - GitHub repo access
9
+ - Hugging Face account
10
+ - Google Colab account (GPU runtime)
11
+
12
+ ## 1) Clone + Setup
13
+
14
+ ```powershell
15
+ git clone https://github.com/Sarthaks-24/sinchan_env.git
16
+ cd sinchan_env
17
+
18
+ py -3 -m pip install -e .
19
+ py -3 -m pip install pytest
20
+ py -3 -m pip install "openenv-core[core]>=0.2.2"
21
+ ```
22
+
23
+ ## 2) Verify Locally
24
+
25
+ ### 2.1 Run tests
26
+
27
+ ```powershell
28
+ py -3 -m pytest -q tests/test_smoke.py
29
+ ```
30
+
31
+ Expected: `7 passed` (or the count printed by pytest; increase if new tests are added).
32
+
33
+ ### 2.2 Start server
34
+
35
+ ```powershell
36
+ py -3 -m uvicorn server.app:app --host 0.0.0.0 --port 8000
37
+ ```
38
+
39
+ Open: `http://localhost:8000/web`
40
+
41
+ Quick manual checks:
42
+ - scenario loads on reset
43
+ - tool actions work
44
+ - reward updates
45
+
46
+ ## 3) Deploy to Hugging Face Space
47
+
48
+ ### 3.1 Create Space (one-time)
49
+
50
+ - Name: `sinchan-env`
51
+ - SDK: `Docker`
52
+ - Visibility: `Public`
53
+ - **App port:** In Space **Settings → App**, set port to **7860** (must match `README` `app_port`, `Dockerfile` `EXPOSE`, and `uvicorn` — if they differ, the UI can show “space in error” while container logs look fine).
54
+
55
+ ### 3.2 Login from terminal
56
+
57
+ ```powershell
58
+ hf auth login
59
+ ```
60
+
61
+ If login fails, create a fresh write token and retry.
62
+
63
+ ### 3.3 Push environment
64
+
65
+ ```powershell
66
+ py -3 -m openenv.cli push --repo-id Gladiator-codes/sinchan-env .
67
+ ```
68
+
69
+ If `openenv` is on your `PATH`, you can use `openenv push ...` instead. Do **not** use `python -m openenv` — that package has no `__main__` module.
70
+
71
+ ### 3.4 Check Space health
72
+
73
+ - Space card: [Gladiator-codes/sinchan-env](https://huggingface.co/spaces/Gladiator-codes/sinchan-env)
74
+ - **Runtime URL to use in Colab / `ENV_URL` when the default host is stuck in “error”:**
75
+ `https://gladiator-codes-sinchan-env-a446abd.hf.space`
76
+ (Hugging Face sometimes serves a **revision** hostname with a middle segment like `‑a446abd` that works even when the short `gladiator-codes-sinchan-env.hf.space` URL does not. That suffix can **change** after a new build — if training suddenly cannot connect, copy the current host from the working Space / Playground in the browser.)
77
+ - Check logs until app is healthy
78
+
79
+ ### 3.5 Release verification (deployment drift / “A”)
80
+
81
+ Local tests passing does **not** mean the public Space is running the same code. Before you debug Colab or clients:
82
+
83
+ 1. **Hub build:** In the Space, open **Settings → App** (or the build tab) and confirm a **build completed after** the commit you care about. If there is no recent build, your changes are not live yet.
84
+ 2. **Match Colab to Space:** The notebook clones `main` by default. If you need a specific fix, `git checkout <commit>` in Colab or change `REPO_URL` / use your fork.
85
+ 3. **Browser checks (warm then cold if possible):**
86
+ - `https://YOUR-SPACE.hf.space/health` should return `200` (if you get `503`, wait 30–60s and retry; that is often sleep, not your FastAPI).
87
+ - `.../docs` or `.../openapi.json` should load when the app is up.
88
+
89
+ ### 3.6 HTTP-only connectivity (infrastructure / “B”)
90
+
91
+ Hugging Face can serve `/web` (Gradio) while **WebSocket**-based `step` traffic to `/ws` is flaky. Training and the client in this repo are intended to use **HTTP** to `/mcp` and `POST /reset` for `https://*.hf.space`.
92
+
93
+ **From Colab or any machine (copy-paste, stop at first failure):**
94
+
95
+ ```python
96
+ import requests
97
+ BASE = "https://YOUR-SPACE.hf.space".rstrip("/")
98
+ print("health", requests.get(f"{BASE}/health", timeout=20).status_code, requests.get(f"{BASE}/health", timeout=20).text[:200])
99
+ print("reset", requests.post(f"{BASE}/reset", json={}, timeout=30).status_code)
100
+ ```
101
+
102
+ Or use the preflight script (classifies the same path as the client):
103
+
104
+ ```powershell
105
+ py -3 training/preflight_space.py --base-url https://YOUR-SPACE.hf.space --retries 3
106
+ ```
107
+
108
+ If `/health` is `503`, retry with `--retries` or wait; that labels **A/B (wake/proxy)**, not “wrong Python in the app.”
109
+
110
+ ### 3.7 When “Quick Start” in the UI fails (API drift / “C”)
111
+
112
+ - **Do not** use generated Playground text like `CallToolAction(message="...")` for this project. Tools are defined in `server/sinchan_environment.py` (e.g. `choose_action` with `action_name`, `reasoning`, `dialogue`).
113
+ - Prefer `from sinchan_env import SinChanEnv, CallToolAction` (this package re-exports names). A bare `from openenv import CallToolEnv` can fail depending on `openenv-core` version.
114
+ - For hosted URLs, use `SinChanEnv(base_url="https://...", prefer_http_mcp=True)` (default for `https` is HTTP MCP in this client).
115
+
116
+ ### 3.8 Hub CLI and “deploy never happened” (“D”)
117
+
118
+ If `hf auth login` returns **rate limit** or **bad request**, wait, use a **write** token, avoid repeated logins, then run `hf whoami` once. If the Space **Build** tab shows no new build, your `git` changes never reached the image: fix push/auth first, then re-run the checks in **3.5** above.
119
+
120
+ ## 4) Colab Training Flow
121
+
122
+ Notebook path:
123
+ - `training/ShinChan_GRPO_Training.ipynb`
124
+
125
+ In Colab:
126
+ 1. Set runtime to **T4 GPU**
127
+ 2. Open notebook
128
+ 3. Update `ENV_URL` to your HF Space runtime URL
129
+ 4. Run all cells in order
130
+
131
+ The notebook now includes:
132
+ - dependency install
133
+ - health check (`/health`)
134
+ - training command
135
+ - evaluation JSON generation
136
+ - plot PNG generation
137
+
138
+ ## 5) CLI Training (Alternative)
139
+
140
+ ```powershell
141
+ set ENV_URL=https://gladiator-codes-sinchan-env-a446abd.hf.space
142
+ py -3 training/train_sinchan.py --env-url %ENV_URL% --max-steps 200 --dataset-size 200 --learning-rate 1e-5 --num-generations 2 --output-dir training/artifacts/run1
143
+ ```
144
+
145
+ Outputs:
146
+ - `training/artifacts/run1/run_metadata.json`
147
+ - trainer logs/checkpoints
148
+
149
+ ## 6) Evaluation + Plot Generation
150
+
151
+ ### 6.1 Evaluation summary
152
+
153
+ ```powershell
154
+ set ENV_URL=https://gladiator-codes-sinchan-env-a446abd.hf.space
155
+ py -3 training/evaluate_scenarios.py --env-url %ENV_URL% --episodes 10 --output training/artifacts/eval_summary.json
156
+ ```
157
+
158
+ ### 6.2 Plot assets
159
+
160
+ ```powershell
161
+ py -3 -m pip install matplotlib
162
+ py -3 training/plot_metrics.py --run-dir training/artifacts/run1 --eval-summary training/artifacts/eval_summary.json --assets-dir assets
163
+ ```
164
+
165
+ Generated:
166
+ - `assets/reward_curve_total.png`
167
+ - `assets/loss_curve.png` (if loss logs exist)
168
+ - `assets/baseline_comparison.png`
169
+
170
+ ## 7) Final Submission Checklist
171
+
172
+ - [ ] HF Space link works publicly
173
+ - [ ] Colab notebook link works
174
+ - [ ] README has final links + screenshots + plots
175
+ - [ ] Before/after behavior table added
176
+ - [ ] Demo video uploaded (< 2 mins)
177
+ - [ ] Form submitted before deadline
178
+
179
+ ## 8) Common Issues
180
+
181
+ ### `ModuleNotFoundError: openenv`
182
+ Install dependency in the same Python:
183
+
184
+ ```powershell
185
+ py -3 -m pip install "openenv-core[core]>=0.2.2"
186
+ ```
187
+
188
+ ### HF auth `Bad request` or rate limit
189
+ - Wait a bit
190
+ - generate fresh token
191
+ - re-login once (avoid repeated attempts)
192
+
193
+ ### Space stuck in `Starting...`
194
+ - check Build + Container logs
195
+ - confirm app listening port matches runtime expectation
196
+ - restart Space once after successful build
197
+
198
+ ### **All routes return `503` for a long time** (`/`, `/web`, `/health` never become `200`)
199
+
200
+ That is **not** a normal “cold start” after many minutes. The edge proxy has **no healthy container** behind it. Colab cannot fix that; fix the Space.
201
+
202
+ Do this **in order** on [huggingface.co/spaces](https://huggingface.co/spaces):
203
+
204
+ 1. **Build log (Docker):** Open the Space → **Files and versions** or **Build** (or “Build logs”). Did the **last build succeed** (green)? If it **failed**, the image is wrong or missing—fix the error (dependency, Dockerfile, base image pull) and **rebuild**. No amount of retries in Colab helps.
205
+ 2. **App / Container log:** Open **Logs** (runtime). Look for **Python Traceback**, `ModuleNotFoundError`, `Address already in use`, **OOM / Killed**, or the process **exiting**. If uvicorn **never** prints `Application startup complete`, the app **crashes on boot**—that matches endless `503`.
206
+ 3. **Settings → Space hardware:** Confirm the Space is not **paused** (if your plan pauses unused Spaces) and that it has **enough RAM/CPU** for the Docker image (very heavy base images can OOM on small hardware).
207
+ 4. **Port:** This repo’s [`Dockerfile`](Dockerfile) runs `uvicorn` on `0.0.0.0` and `${PORT:-7860}`. In Space settings, **Port** should match what HF expects (often **7860** for Docker SDK). A mismatch can leave the platform routing to nothing → `503`.
208
+ 5. **Factory reboot** after a **green** build: Space menu → **Restart** / “Factory reboot” so a fresh container actually starts.
209
+ 6. **Verify locally (best proof):** From your repo root, `docker build -t sinchan-test .` then `docker run --rm -e PORT=7860 -p 7860:7860 sinchan-test` and open `http://localhost:7860/health`. If that fails, fix **before** pushing to HF again.
210
+
211
+ **Until the Space returns `200` in a normal browser,** set Colab to the **local fallback** (notebook starts `uvicorn` on `127.0.0.1:8000`) or train only against a server you control.
212
+
213
+ ## 9) Security Note
214
+
215
+ - Never paste tokens in shared screenshots/chats/commits.
216
+ - If exposed, revoke immediately and create a new token.
WHAT_TO_DO_NEXT.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What to do next (post-project checklist)
2
+
3
+ After this repository and Space are in good shape, follow these steps in order. Check each box as you go.
4
+
5
+ ## A. Local sanity (5–10 minutes)
6
+
7
+ 1. [ ] In the project root, create/activate a venv and run `pip install -e ".[dev,training]"` (or `uv sync` if you use the lockfile).
8
+ 2. [ ] Start the app: `uv run server` (or `python -m uvicorn server.app:app --host 0.0.0.0 --port 8000` with `PYTHONPATH` set to the repo root if needed).
9
+ 3. [ ] Open in a browser:
10
+ - [ ] `http://localhost:8000/health` → `{"status":"ok"}` (or equivalent)
11
+ - [ ] `http://localhost:8000/gradio` → Gradio UI loads; **New episode** + one action returns JSON with a numeric **reward**
12
+ - [ ] `http://localhost:8000/blog.md` → markdown loads (same content you link from the README)
13
+ 4. [ ] `python -m pytest -q tests/test_smoke.py` passes.
14
+ 5. [ ] (Optional) `python training/stage1_validate_env.py --env-url http://127.0.0.1:8000` while the server runs — you should see printed transitions and `training/artifacts/stage1_validation.json` created.
15
+
16
+ ## B. Hugging Face Space deployment
17
+
18
+ 1. [ ] `hf auth login` on the machine you deploy from.
19
+ 2. [ ] From the **repository root** (where `openenv.yaml` and `Dockerfile` live), run:
20
+ `openenv push --repo-id <your-username-or-org>/<your-space> .`
21
+ (On Windows, `py -3 -m openenv.cli push ...` if the CLI is not on `PATH`.)
22
+ 3. [ ] In the Space **Settings**, confirm: Docker build, **port 7860** (or the port your `CMD` / `PORT` uses), and enough CPU/RAM to boot.
23
+ 4. [ ] When the build finishes, open the **Space URL** in a new tab to wake the container. Cold starts on free tier can take **1–3+ minutes** and may return 503 on `/health` briefly.
24
+ 5. [ ] Copy the **runtime** base URL (the one that actually loads the UI, often `https://<name>-<hash>.hf.space` if the short URL errors).
25
+ 6. [ ] Run:
26
+ `python training/preflight_space.py --base-url <RUNTIME_BASE_URL> --retries 5`
27
+ from this repo. All checks should pass.
28
+ 7. [ ] In the browser, verify: `<RUNTIME_BASE_URL>/gradio`, `<RUNTIME_BASE_URL>/blog.md`, and `<RUNTIME_BASE_URL>/web` (or your chosen OpenEnv route).
29
+
30
+ ## C. Colab: end-to-end training proof
31
+
32
+ 1. [ ] Open `training/ShinChan_GRPO_Training.ipynb` in **Google Colab** (link in README).
33
+ 2. [ ] **Runtime → Change runtime type → GPU** (T4 is enough). CPU training is possible but very slow and QLoRA will not work.
34
+ 3. [ ] First cell: updates `openenv-core[core]>=0.2.3` and installs **TRL, transformers, jmespath, matplotlib** (and for QLoRA: `peft`, `bitsandbytes` when you add the optional cell).
35
+ 4. [ ] Set `ENV_URL` to the **Space runtime** URL from B.5 (not the `huggingface.co/spaces/...` repo page).
36
+ 5. [ ] Run the connectivity probe cell until it succeeds (or the notebook’s local fallback, if you use it).
37
+ 6. [ ] Run **Stage 1** (optional) `stage1_validate_env.py` to confirm the remote environment responds.
38
+ 7. [ ] Run **Stage 2** (short GRPO) first if you need a **quick proof**; then **Stage 3** for a longer run. Confirm `tqdm` / logs stream (do not `capture_output=True` in subprocess).
39
+ 8. [ ] After training, run **eval** and **plot** cells so `assets/reward_curve_total.png` and `assets/loss_curve.png` exist. Open the files in the Colab file tree to verify they are **non-placeholder** (axes, multiple points).
40
+ 9. [ ] If you use **W&B**, set `WANDB_API_KEY` in Colab; otherwise rely on the saved PNGs + JSON/JSONL in `training/artifacts/`.
41
+ 10. [ ] **Download** `training/artifacts/run1/`, `training/artifacts/eval_summary.json`, and `assets/*.png` to your machine if you will commit them to Git.
42
+
43
+ ## D. Repository hygiene for judges
44
+
45
+ 1. [ ] **Do not** commit: large checkpoints, `.safetensors` blobs, `venv/`, or anything under `trash/` (that folder is gitignored).
46
+ 2. [ ] **Do** commit: small JSON (`eval_summary`, `run_metadata`, `stage4_report` if you keep it), small PNGs, and updated `README` links.
47
+ 3. [ ] In the README, set the **Colab** link, **Space** link, and **blog** link (`/blog.md` on the Space).
48
+ 4. [ ] Update the “before / after” table with numbers from your **eval JSON** and training summary (see README section 6).
49
+
50
+ ## E. If something breaks
51
+
52
+ - **Remote 503 on `/health`:** wait, refresh the Space, open the Space in a normal browser tab to wake the proxy; retry `preflight_space.py` with a higher `--retries`.
53
+ - **Connection errors in training:** use `prefer_http_mcp=True` for `https` (already the default in the client) and check Space logs for Python stack traces.
54
+ - **No reward/loss curves:** ensure `train_sinchan.py` ran with `logging_steps=1` and that `metrics.jsonl` exists under the run directory; re-run `plot_metrics.py` with the correct `--run-dir`.
55
+ - **Gradio 404 on Space:** confirm you deployed the current `server/app.py` and that the container rebuilt; the route is `/gradio`.
56
+
57
+ ## F. Submission day
58
+
59
+ 1. [ ] Re-run B (preflight) and C.7–C.8 on a **clean** Colab runtime (or document exact versions in `run_metadata.json`).
60
+ 2. [ ] Tag the git commit you submit: `v1.0-hackathon` (optional).
61
+ 3. [ ] Double-check the hackathon form fields: **Space URL**, **Colab URL**, **repo URL**, and **one short write-up** (this repo uses `blog.md` on the Space as that write-up; add a public video link only if the rules require it).
62
+
63
+ You are done when: **Space is up**, **Colab runs end-to-end without manual patches**, and **curves + JSON** are in the repo (or on Hub) with no multi‑gigabyte files in Git.
__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ ShinChan Life Simulator — An OpenEnv MCP environment for RL training.
6
+
7
+ This environment simulates Shin-chan Nohara's daily life situations where
8
+ an LLM agent must make decisions while staying in character. Through RL
9
+ training, the agent learns to make better choices while maintaining
10
+ Shin-chan's unique personality.
11
+
12
+ Tools exposed via MCP:
13
+ - `choose_action(action_name, reasoning, dialogue)`: Make a decision as Shin-chan
14
+ - `get_scenario_info()`: Get information about the current scenario
15
+ - `get_relationships()`: View current relationship status with all characters
16
+
17
+ Example:
18
+ >>> from sinchan_env import SinChanEnv
19
+ >>>
20
+ >>> with SinChanEnv(base_url="http://localhost:8000") as env:
21
+ ... env.reset()
22
+ ... tools = env.list_tools()
23
+ ... result = env.call_tool("get_scenario_info")
24
+ ... print(result)
25
+ ... result = env.call_tool("choose_action",
26
+ ... action_name="do_homework",
27
+ ... reasoning="Mom is angry and homework is due tomorrow",
28
+ ... dialogue="Buri buri~ fine, I'll do it... but only if there's Chocobi after!")
29
+ ... print(result)
30
+ """
31
+
32
+ # Re-export MCP types for convenience
33
+ from openenv.core.env_server.mcp_types import CallToolAction, ListToolsAction
34
+
35
+ from .client import CallToolEnv, SinChanEnv
36
+
37
+ __all__ = ["SinChanEnv", "CallToolEnv", "CallToolAction", "ListToolsAction"]
assets/README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plot assets (submission)
2
+
3
+ PNG charts are **not** committed as large binaries from CI by default. Generate them locally or in Colab after a real run:
4
+
5
+ ```bash
6
+ python training/plot_metrics.py \
7
+ --run-dir training/artifacts/run1 \
8
+ --eval-summary training/artifacts/eval_summary.json \
9
+ --assets-dir assets
10
+ ```
11
+
12
+ Expected outputs:
13
+
14
+ - `reward_curve_total.png` — from `metrics.jsonl` / `trainer_state.json` reward keys.
15
+ - `loss_curve.png` — from logged `loss` / `train/loss` keys.
16
+ - `baseline_comparison.png` — from `evaluate_scenarios.py` JSON (`random` vs `rule_based`).
17
+
18
+ The Colab notebook includes a cell that runs the same plotting command. Commit the resulting small PNGs for judges (typically well under 1 MB total).
assets/baseline_comparison.png ADDED
assets/loss_curve.png ADDED
assets/reward_curve_total.png ADDED
client.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ ShinChan Life Simulator Client.
6
+
7
+ This module provides the client for connecting to a ShinChan Environment server.
8
+ SinChanEnv extends MCPToolClient to provide tool-calling style interactions.
9
+
10
+ Example:
11
+ >>> with SinChanEnv(base_url="http://localhost:8000") as env:
12
+ ... env.reset()
13
+ ...
14
+ ... # Discover tools
15
+ ... tools = env.list_tools()
16
+ ... print([t.name for t in tools])
17
+ ...
18
+ ... # Get scenario info
19
+ ... info = env.call_tool("get_scenario_info")
20
+ ... print(info)
21
+ ...
22
+ ... # Make a decision
23
+ ... result = env.call_tool("choose_action",
24
+ ... action_name="do_homework",
25
+ ... reasoning="Homework is due tomorrow and Mom is angry",
26
+ ... dialogue="Buri buri~ fine, I'll do it!")
27
+ ... print(result)
28
+ """
29
+
30
+ import os
31
+ from typing import Any
32
+
33
+ from openenv.core.client_types import StepResult
34
+ from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
35
+ from openenv.core.mcp_client import MCPToolClient
36
+
37
+
38
+ class SinChanEnv(MCPToolClient):
39
+ """
40
+ Client for the ShinChan Life Simulator Environment.
41
+
42
+ This client provides a simple interface for interacting with the ShinChan
43
+ Environment via MCP tools. It inherits all functionality from MCPToolClient:
44
+ - `list_tools()`: Discover available tools
45
+ - `call_tool(name, **kwargs)`: Call a tool by name
46
+ - `reset(**kwargs)`: Reset the environment
47
+ - `step(action)`: Execute an action (for advanced use)
48
+
49
+ Available Tools:
50
+ - `choose_action(action_name, reasoning, dialogue)`: Make a decision
51
+ - `get_scenario_info()`: Get current scenario details
52
+ - `get_relationships()`: View relationship meters
53
+
54
+ Example with sync API:
55
+ >>> with SinChanEnv(base_url="http://localhost:8000") as env:
56
+ ... env.reset()
57
+ ... tools = env.list_tools()
58
+ ... result = env.call_tool("choose_action",
59
+ ... action_name="do_homework",
60
+ ... reasoning="Mom is angry",
61
+ ... dialogue="Fine, I'll do it!")
62
+
63
+ Example with HuggingFace Space:
64
+ >>> env = SinChanEnv(base_url="https://gladiator-codes-sinchan-env-a446abd.hf.space")
65
+ >>> try:
66
+ ... env.reset()
67
+ ... result = env.call_tool("get_scenario_info")
68
+ ... finally:
69
+ ... env.close()
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ base_url: str,
75
+ connect_timeout_s: float = 10.0,
76
+ message_timeout_s: float = 60.0,
77
+ prefer_http_mcp: bool | None = None,
78
+ ) -> None:
79
+ """
80
+ Build a client with optional HTTP MCP preference.
81
+
82
+ For hosted environments (e.g. HF Spaces), HTTP MCP is often more
83
+ reliable than direct websocket step traffic.
84
+ """
85
+ super().__init__(
86
+ base_url=base_url,
87
+ connect_timeout_s=connect_timeout_s,
88
+ message_timeout_s=message_timeout_s,
89
+ )
90
+ if prefer_http_mcp is None:
91
+ prefer_http_mcp = (
92
+ base_url.startswith("https://")
93
+ or os.environ.get("OPENENV_PREFER_HTTP_MCP", "1") == "1"
94
+ )
95
+ self.use_production_mode = bool(prefer_http_mcp)
96
+
97
+ async def step(self, action: Any, **kwargs: Any) -> StepResult[Any]:
98
+ """
99
+ Execute one action.
100
+
101
+ In HTTP MCP mode, map CallToolAction to call_tool so hosted deployments
102
+ can work without websocket step transport.
103
+ """
104
+ if self.use_production_mode and isinstance(action, CallToolAction):
105
+ arguments = action.arguments if isinstance(action.arguments, dict) else {}
106
+ result = await self.call_tool(action.tool_name, **arguments)
107
+
108
+ result_dict = result if isinstance(result, dict) else {}
109
+ reward = float(result_dict.get("reward", 0.0) or 0.0)
110
+ done = bool(result_dict.get("done", False))
111
+ metadata = result_dict.get("reward_components")
112
+ if not isinstance(metadata, dict):
113
+ metadata = {}
114
+
115
+ observation = CallToolObservation(
116
+ tool_name=action.tool_name,
117
+ result=result,
118
+ error=None,
119
+ done=done,
120
+ reward=reward,
121
+ metadata=metadata,
122
+ )
123
+ return StepResult(observation=observation, reward=reward, done=done)
124
+
125
+ return await super().step(action, **kwargs)
126
+
127
+
128
+ class CallToolEnv(SinChanEnv):
129
+ """Compatibility alias used by some generated OpenEnv quick-start snippets."""
130
+
131
+ @classmethod
132
+ def from_env(cls, name: str, **kwargs: Any):
133
+ """
134
+ Synchronous helper for Hub environments.
135
+
136
+ Returns a sync wrapper so users can write:
137
+ with CallToolEnv.from_env("user/repo") as env:
138
+ ...
139
+ """
140
+ import asyncio
141
+
142
+ try:
143
+ asyncio.get_running_loop()
144
+ except RuntimeError:
145
+ async_client = asyncio.run(super().from_env(name, **kwargs))
146
+ return async_client.sync()
147
+
148
+ raise RuntimeError(
149
+ "CallToolEnv.from_env() sync helper cannot run inside an active "
150
+ "event loop. Use `client = await SinChanEnv.from_env(...)` in async code."
151
+ )
models.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ OpenEnv Type Models for ShinChan Life Simulator.
6
+
7
+ Defines the Action and Observation types for the environment.
8
+ These are used for type validation and client/server communication.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Optional
13
+
14
+
15
+ @dataclass
16
+ class SinChanAction:
17
+ """Action taken by the agent in the ShinChan environment."""
18
+
19
+ action_name: str # Name of the action to take (e.g., 'do_homework')
20
+ reasoning: str # Agent's thought process for choosing this action
21
+ dialogue: str # What Shin-chan says (should stay in character)
22
+
23
+
24
+ @dataclass
25
+ class SinChanObservation:
26
+ """Observation returned by the environment after an action."""
27
+
28
+ narrative: str # Story continuation describing what happened
29
+ character_reactions: str # How NPCs reacted to the action
30
+ available_actions: list[dict] = field(
31
+ default_factory=list
32
+ ) # List of actions Shin-chan can take next
33
+ relationships: dict[str, float] = field(
34
+ default_factory=dict
35
+ ) # Current relationship meters with characters
36
+ reward_breakdown: dict[str, float] = field(
37
+ default_factory=dict
38
+ ) # Detailed reward components
39
+ done: bool = False # Is the scenario complete?
40
+ reward: float = 0.0 # Total reward for this step
41
+
42
+
43
+ @dataclass
44
+ class SinChanState:
45
+ """Internal state of the environment."""
46
+
47
+ episode_id: str # Unique episode identifier
48
+ scenario_id: str # Current scenario ID
49
+ step_count: int # Number of steps taken so far
50
+ max_steps: int # Maximum steps allowed in this scenario
51
+ category: str # Scenario category (school, family, social, etc.)
52
+ difficulty: int # Difficulty level (1-5)
53
+ relationships: dict[str, float] = field(
54
+ default_factory=dict
55
+ ) # Relationship state with all characters
openenv.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: sinchan_env
3
+ type: space
4
+ runtime: fastapi
5
+ app: server.app:app
6
+ port: 7860
pyproject.toml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=45", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "openenv-sinchan-env"
7
+ version = "0.1.0"
8
+ description = "ShinChan Life Simulator — An OpenEnv RL environment where LLMs learn from Shin-chan's mistakes!"
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ # Core OpenEnv dependencies (required for server functionality)
12
+ "openenv-core[core]>=0.2.3",
13
+ "fastapi>=0.115.0",
14
+ "pydantic>=2.0.0",
15
+ "uvicorn>=0.24.0",
16
+ "requests>=2.31.0",
17
+ "fastmcp>=0.1.0",
18
+ "gradio>=4.0.0",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ dev = [
23
+ "pytest>=9.0.3",
24
+ "pytest-cov>=4.0.0",
25
+ ]
26
+ training = [
27
+ "trl>=0.12.0",
28
+ "datasets>=2.14.0",
29
+ "torch>=2.0.0",
30
+ "transformers>=5.2.0",
31
+ "jmespath>=1.0.0",
32
+ "peft>=0.11.0",
33
+ "bitsandbytes>=0.42.0",
34
+ "matplotlib>=3.8.0",
35
+ ]
36
+
37
+ [project.scripts]
38
+ # Server entry point - enables running via: uv run --project . server
39
+ server = "sinchan_env.server.app:main"
40
+
41
+ [tool.setuptools]
42
+ include-package-data = true
43
+ packages = ["sinchan_env", "sinchan_env.server"]
44
+ package-dir = { "sinchan_env" = ".", "sinchan_env.server" = "server" }
45
+
46
+ [tool.setuptools.package-data]
47
+ "sinchan_env.server" = ["static/sinchan/index.html", "static/blog.md"]
server/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
2
+ FROM ${BASE_IMAGE} AS builder
3
+
4
+ WORKDIR /app
5
+ COPY . /app/env
6
+ WORKDIR /app/env
7
+
8
+ RUN if ! command -v uv >/dev/null 2>&1; then \
9
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
10
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
11
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
12
+ fi
13
+
14
+ RUN apt-get update && apt-get install -y --no-install-recommends \
15
+ git \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ RUN --mount=type=cache,target=/root/.cache/uv \
19
+ if [ -f uv.lock ]; then \
20
+ uv sync --frozen --no-install-project --no-editable; \
21
+ else \
22
+ uv sync --no-install-project --no-editable; \
23
+ fi
24
+
25
+ RUN --mount=type=cache,target=/root/.cache/uv \
26
+ if [ -f uv.lock ]; then \
27
+ uv sync --frozen --no-editable; \
28
+ else \
29
+ uv sync --no-editable; \
30
+ fi
31
+
32
+ FROM ${BASE_IMAGE}
33
+
34
+ WORKDIR /app
35
+ COPY --from=builder /app/env/.venv /app/.venv
36
+ COPY --from=builder /app/env /app/env
37
+
38
+ ENV PATH="/app/.venv/bin:$PATH"
39
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
40
+ ENV ENABLE_WEB_INTERFACE=true
41
+
42
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port ${PORT:-7860}"]
server/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # ShinChan Life Simulator — Server Package
server/app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ FastAPI application for the ShinChan Environment.
6
+
7
+ Usage:
8
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
9
+ uv run --project . server
10
+ """
11
+
12
+ import os
13
+
14
+ from fastapi import FastAPI
15
+ from fastapi.responses import FileResponse, RedirectResponse
16
+ from fastapi.staticfiles import StaticFiles
17
+ from gradio import mount_gradio_app
18
+
19
+ from .gradio_ui import make_demo
20
+
21
+ try:
22
+ from openenv.core.env_server.http_server import create_app
23
+ from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
24
+ from .sinchan_environment import SinChanEnvironment
25
+ except ImportError:
26
+ from openenv.core.env_server.http_server import create_app
27
+ from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
28
+ from server.sinchan_environment import SinChanEnvironment
29
+
30
+ # Enable OpenEnv web UI by default for local runs (/web route).
31
+ # Can still be overridden externally by setting ENABLE_WEB_INTERFACE.
32
+ os.environ.setdefault("ENABLE_WEB_INTERFACE", "true")
33
+
34
+ max_concurrent = int(os.getenv("MAX_CONCURRENT_ENVS", "32"))
35
+
36
+ app = create_app(
37
+ SinChanEnvironment,
38
+ CallToolAction,
39
+ CallToolObservation,
40
+ env_name="sinchan_env",
41
+ max_concurrent_envs=max_concurrent,
42
+ )
43
+
44
+
45
+ def _has_route_path(fastapi_app: FastAPI, path: str) -> bool:
46
+ """Return True when a route with exact path is already registered."""
47
+ return any(getattr(route, "path", None) == path for route in fastapi_app.routes)
48
+
49
+
50
+ if not _has_route_path(app, "/health"):
51
+ @app.get("/health")
52
+ def health() -> dict[str, str]:
53
+ """Readiness endpoint for Spaces/Colab probes."""
54
+ return {"status": "ok"}
55
+
56
+ _BLOG_FILE = os.path.join(os.path.dirname(__file__), "static", "blog.md")
57
+ if os.path.isfile(_BLOG_FILE) and not _has_route_path(app, "/blog.md"):
58
+
59
+ @app.get("/blog.md")
60
+ def blog_markdown() -> FileResponse:
61
+ """Hackathon mini-blog (link this URL from the README)."""
62
+ return FileResponse(_BLOG_FILE, media_type="text/markdown; charset=utf-8")
63
+
64
+ _SINCHAN_UI_DIR = os.path.join(os.path.dirname(__file__), "static", "sinchan")
65
+ if os.path.isdir(_SINCHAN_UI_DIR):
66
+ app.mount(
67
+ "/sinchan-ui",
68
+ StaticFiles(directory=_SINCHAN_UI_DIR, html=True),
69
+ name="sinchan_ui",
70
+ )
71
+
72
+ if not _has_route_path(app, "/play"):
73
+ @app.get("/play", tags=["ShinChan UI"])
74
+ def play_lobby() -> RedirectResponse:
75
+ """Crayon-style browser UI. The OpenEnv lab remains at /web when enabled."""
76
+ return RedirectResponse(url="/sinchan-ui/", status_code=302)
77
+
78
+ # Gradio: simple state / action / reward UI (OpenEnv + REST remain on other routes)
79
+ if not _has_route_path(app, "/gradio"):
80
+ mount_gradio_app(app, make_demo(), path="/gradio")
81
+
82
+ def main():
83
+ """Entry point for direct execution."""
84
+ import uvicorn
85
+ port = int(os.getenv("PORT", "8000"))
86
+ uvicorn.run(app, host="0.0.0.0", port=port)
87
+
88
+ if __name__ == "__main__":
89
+ main()
server/characters.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ NPC Character System for ShinChan Life Simulator.
6
+
7
+ Contains personality profiles and reaction logic for all characters
8
+ in Shin-chan's world. Each character has defined personality traits,
9
+ triggers, and reaction patterns that determine how they respond to
10
+ the agent's actions.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+
18
+ @dataclass
19
+ class Character:
20
+ """A character in Shin-chan's world with personality and reaction logic."""
21
+
22
+ id: str
23
+ name: str
24
+ relationship_to_shinchan: str
25
+ personality: str
26
+ anger_triggers: list[str] = field(default_factory=list)
27
+ happy_triggers: list[str] = field(default_factory=list)
28
+ reaction_style: str = ""
29
+ catchphrases: list[str] = field(default_factory=list)
30
+ initial_relationship: float = 0.5 # 0.0 = hostile, 1.0 = best friends
31
+
32
+ def get_reaction(self, action_name: str, action_tags: list[str]) -> tuple[str, float]:
33
+ """
34
+ Generate a reaction to Shin-chan's action.
35
+
36
+ Returns:
37
+ Tuple of (reaction_text, relationship_change)
38
+ """
39
+ # Check for anger triggers
40
+ for tag in action_tags:
41
+ if tag in self.anger_triggers:
42
+ return self._angry_reaction(action_name), -0.15
43
+
44
+ # Check for happy triggers
45
+ for tag in action_tags:
46
+ if tag in self.happy_triggers:
47
+ return self._happy_reaction(action_name), 0.10
48
+
49
+ # Neutral reaction
50
+ return self._neutral_reaction(action_name), 0.0
51
+
52
+ def _angry_reaction(self, action_name: str) -> str:
53
+ return f"{self.name} is upset! {self.reaction_style}"
54
+
55
+ def _happy_reaction(self, action_name: str) -> str:
56
+ return f"{self.name} is pleased! They appreciate Shin-chan's effort."
57
+
58
+ def _neutral_reaction(self, action_name: str) -> str:
59
+ return f"{self.name} watches quietly."
60
+
61
+
62
+ # ============================================================================
63
+ # CHARACTER DATABASE
64
+ # ============================================================================
65
+
66
+ CHARACTERS: dict[str, Character] = {
67
+ "misae": Character(
68
+ id="misae",
69
+ name="Misae Nohara (Mom)",
70
+ relationship_to_shinchan="Mother",
71
+ personality=(
72
+ "Short-tempered but deeply loving. Wants Shin-chan to be responsible "
73
+ "and well-behaved. Quick to anger but also quick to forgive. She works "
74
+ "hard to manage the household and worries about Shin-chan's future."
75
+ ),
76
+ anger_triggers=[
77
+ "lying", "being_lazy", "embarrassing", "wasting_money",
78
+ "skipping_homework", "being_rude", "making_mess", "disobedient",
79
+ "sneaking", "ignoring_duties",
80
+ ],
81
+ happy_triggers=[
82
+ "doing_homework", "being_honest", "helping_house", "being_responsible",
83
+ "caring_for_himawari", "being_polite", "saving_money", "studying",
84
+ "cleaning", "apologizing",
85
+ ],
86
+ reaction_style="Explosive anger → loud scolding → eventual forgiveness.",
87
+ catchphrases=[
88
+ "SHIN-CHAN!! 💢",
89
+ "How many times do I have to tell you?!",
90
+ "That's it, no dinner for you!",
91
+ "Maybe you're growing up after all... *sniff*",
92
+ ],
93
+ initial_relationship=0.7,
94
+ ),
95
+ "hiroshi": Character(
96
+ id="hiroshi",
97
+ name="Hiroshi Nohara (Dad)",
98
+ relationship_to_shinchan="Father",
99
+ personality=(
100
+ "Hardworking salaryman who is often tired but loves his family dearly. "
101
+ "More lenient than Misae. Enjoys his small pleasures (beer, manga). "
102
+ "Sometimes acts as an accomplice to Shin-chan's antics."
103
+ ),
104
+ anger_triggers=[
105
+ "wasting_money", "being_rude", "embarrassing", "lying",
106
+ ],
107
+ happy_triggers=[
108
+ "being_honest", "being_responsible", "caring_for_family",
109
+ "helping_house", "being_brave", "showing_maturity",
110
+ ],
111
+ reaction_style="Sighs and gentle scolding, sometimes secretly amused.",
112
+ catchphrases=[
113
+ "Shin-chan, you rascal...",
114
+ "Your mother is going to kill us both.",
115
+ "That's my boy!",
116
+ "*sigh* Where did I go wrong...",
117
+ ],
118
+ initial_relationship=0.75,
119
+ ),
120
+ "himawari": Character(
121
+ id="himawari",
122
+ name="Himawari Nohara (Baby Sister)",
123
+ relationship_to_shinchan="Baby sister",
124
+ personality=(
125
+ "Cute baby who loves shiny things and handsome men. Often cries when "
126
+ "neglected. Looks up to Shin-chan despite his antics. Can be surprisingly "
127
+ "perceptive for a baby."
128
+ ),
129
+ anger_triggers=[
130
+ "ignoring_duties", "being_selfish", "stealing_food", "being_mean",
131
+ ],
132
+ happy_triggers=[
133
+ "caring_for_himawari", "sharing", "playing_together", "being_gentle",
134
+ ],
135
+ reaction_style="Cries loudly or giggles happily — no in-between.",
136
+ catchphrases=["Waaah! 😭", "Tee hee! 😊", "*grabs shiny thing*"],
137
+ initial_relationship=0.6,
138
+ ),
139
+ "kazama": Character(
140
+ id="kazama",
141
+ name="Kazama Toru",
142
+ relationship_to_shinchan="Best friend",
143
+ personality=(
144
+ "Studious, serious, and ambitious. The most mature of Shin-chan's friend "
145
+ "group. Gets easily annoyed by Shin-chan's antics but secretly values "
146
+ "their friendship. Dreams of becoming an elite businessman."
147
+ ),
148
+ anger_triggers=[
149
+ "being_lazy", "not_studying", "embarrassing", "being_rude",
150
+ "cheating", "lying",
151
+ ],
152
+ happy_triggers=[
153
+ "studying", "being_honest", "teamwork", "showing_effort",
154
+ "being_brave", "helping_friends",
155
+ ],
156
+ reaction_style="Lectures Shin-chan but secretly cares.",
157
+ catchphrases=[
158
+ "Nohara, you idiot!",
159
+ "I'm not your friend! ...Well, maybe a little.",
160
+ "You should study more like me.",
161
+ "I guess that was... pretty cool of you.",
162
+ ],
163
+ initial_relationship=0.65,
164
+ ),
165
+ "nene": Character(
166
+ id="nene",
167
+ name="Sakurada Nene",
168
+ relationship_to_shinchan="Friend",
169
+ personality=(
170
+ "Appears sweet and girly but has a hidden fierce side. Loves playing "
171
+ "'real house' (with extreme realism). Can be bossy and gets angry "
172
+ "when things don't go her way. Punches her stuffed rabbit when upset."
173
+ ),
174
+ anger_triggers=[
175
+ "being_rude", "refusing_to_play", "lying", "being_mean",
176
+ "embarrassing",
177
+ ],
178
+ happy_triggers=[
179
+ "playing_together", "being_polite", "helping_friends",
180
+ "being_honest", "showing_empathy",
181
+ ],
182
+ reaction_style="Sweet on the surface, then suddenly furious. Punches Mr. Rabbit.",
183
+ catchphrases=[
184
+ "Let's play REAL house!",
185
+ "Mr. Rabbit... *punch punch punch*",
186
+ "Shin-chan, you're so mean!",
187
+ "That's actually really nice of you.",
188
+ ],
189
+ initial_relationship=0.55,
190
+ ),
191
+ "bo": Character(
192
+ id="bo",
193
+ name="Tooru Bo (Bo-chan)",
194
+ relationship_to_shinchan="Friend",
195
+ personality=(
196
+ "Quiet, mysterious, and zen-like. Rarely speaks but when he does, "
197
+ "it's profound (or completely random). Has a calming presence. "
198
+ "Often just says '...' but somehow communicates perfectly."
199
+ ),
200
+ anger_triggers=["being_mean", "bullying"],
201
+ happy_triggers=[
202
+ "being_honest", "showing_kindness", "being_brave", "teamwork",
203
+ ],
204
+ reaction_style="Silent nod of approval, or a quiet '...'",
205
+ catchphrases=["...", "...!!", "Mm.", "...that was good."],
206
+ initial_relationship=0.6,
207
+ ),
208
+ "masao": Character(
209
+ id="masao",
210
+ name="Sato Masao",
211
+ relationship_to_shinchan="Friend",
212
+ personality=(
213
+ "Timid, easily scared, and often crying. A crybaby who gets picked on "
214
+ "but is genuinely kind-hearted. Looks up to others for protection. "
215
+ "Despite his fears, he can be surprisingly loyal."
216
+ ),
217
+ anger_triggers=["bullying", "being_mean", "lying"],
218
+ happy_triggers=[
219
+ "helping_friends", "being_brave", "showing_kindness",
220
+ "sharing", "protecting_others",
221
+ ],
222
+ reaction_style="Cries easily but shows gratitude through tears.",
223
+ catchphrases=[
224
+ "Waaah, I'm scared! 😭",
225
+ "Shin-chan, help me!",
226
+ "Thank you... *sniff*",
227
+ "You're so cool, Shin-chan!",
228
+ ],
229
+ initial_relationship=0.6,
230
+ ),
231
+ "yoshinaga": Character(
232
+ id="yoshinaga",
233
+ name="Yoshinaga Midori (Teacher)",
234
+ relationship_to_shinchan="Kindergarten teacher",
235
+ personality=(
236
+ "Kind but strict kindergarten teacher at Futaba Kindergarten. Unmarried "
237
+ "and a bit insecure about it (Shin-chan often brings this up). Patient "
238
+ "but has her limits. Genuinely cares about her students' growth."
239
+ ),
240
+ anger_triggers=[
241
+ "being_rude", "skipping_homework", "cheating", "embarrassing",
242
+ "disobedient", "making_mess",
243
+ ],
244
+ happy_triggers=[
245
+ "studying", "doing_homework", "being_polite", "showing_effort",
246
+ "being_honest", "helping_friends",
247
+ ],
248
+ reaction_style="Patient sighing, then firm but caring discipline.",
249
+ catchphrases=[
250
+ "Shin-chan, please behave!",
251
+ "Don't bring up my love life! 😤",
252
+ "I'm proud of you today.",
253
+ "That's what learning is all about!",
254
+ ],
255
+ initial_relationship=0.5,
256
+ ),
257
+ "shiro": Character(
258
+ id="shiro",
259
+ name="Shiro (Dog)",
260
+ relationship_to_shinchan="Pet dog",
261
+ personality=(
262
+ "Incredibly smart and loyal dog. Often more sensible than Shin-chan. "
263
+ "Patient, obedient, and sometimes the voice of reason (in dog form). "
264
+ "Gets sad when neglected but always forgives."
265
+ ),
266
+ anger_triggers=["ignoring_duties", "being_mean"],
267
+ happy_triggers=[
268
+ "caring_for_shiro", "playing_together", "being_responsible",
269
+ "sharing",
270
+ ],
271
+ reaction_style="Wags tail happily or whimpers sadly.",
272
+ catchphrases=["Wan! 🐕", "*wag wag*", "*whimper*", "*happy bark!*"],
273
+ initial_relationship=0.7,
274
+ ),
275
+ }
276
+
277
+
278
+ def get_character(character_id: str) -> Character | None:
279
+ """Get a character by their ID."""
280
+ return CHARACTERS.get(character_id)
281
+
282
+
283
+ def get_all_characters() -> dict[str, Character]:
284
+ """Get all characters."""
285
+ return CHARACTERS.copy()
286
+
287
+
288
+ def get_characters_by_ids(character_ids: list[str]) -> list[Character]:
289
+ """Get multiple characters by their IDs."""
290
+ return [CHARACTERS[cid] for cid in character_ids if cid in CHARACTERS]
server/gradio_ui.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ """Gradio UI: run the Shin-chan environment in-process (no extra HTTP hop)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import random
8
+
9
+ import gradio as gr
10
+ from openenv.core.env_server.mcp_types import CallToolAction
11
+
12
+ from .sinchan_environment import SinChanEnvironment
13
+
14
+ # Single in-process environment for the Space (demo-style; not multi-tenant).
15
+ _UI_ENV: SinChanEnvironment | None = None
16
+
17
+
18
+ def _get_env() -> SinChanEnvironment:
19
+ global _UI_ENV
20
+ if _UI_ENV is None:
21
+ _UI_ENV = SinChanEnvironment()
22
+ return _UI_ENV
23
+
24
+
25
+ def _obs_result(obs) -> dict:
26
+ """
27
+ Unwrap OpenEnv / MCP `Observation` into a dict (same as tests/test_smoke.py).
28
+ Tool outputs are often JSON text inside result.content[0], not a bare dict.
29
+ """
30
+ result = getattr(obs, "result", None)
31
+ if isinstance(result, dict):
32
+ return result
33
+ content = getattr(result, "content", None)
34
+ if isinstance(content, list) and content:
35
+ text = getattr(content[0], "text", "")
36
+ if isinstance(text, str) and text.strip():
37
+ try:
38
+ return json.loads(text)
39
+ except json.JSONDecodeError:
40
+ return {"_parse_error": "non-json tool payload", "raw": text[:2000]}
41
+ return {}
42
+
43
+
44
+ def _fmt_state(info: dict) -> str:
45
+ if not info:
46
+ return "_No scenario data — click **New episode**._"
47
+ if info.get("error"):
48
+ return f"**Error:** {info.get('error')}"
49
+ title = info.get("title") or "Scenario"
50
+ narr = (info.get("narrative") or "").strip()
51
+ people = info.get("characters_involved") or []
52
+ ppl = ", ".join(
53
+ f"{c.get('name', '?')}" for c in people if isinstance(c, dict)
54
+ )
55
+ parts = [f"## {title}", ""]
56
+ if ppl:
57
+ parts.append(f"**People involved:** {ppl}")
58
+ parts.append("")
59
+ parts.append(narr if narr else "_(no narrative text)_")
60
+ parts.append("")
61
+ parts.append("### Pick an action")
62
+ for a in info.get("available_actions") or []:
63
+ if not isinstance(a, dict):
64
+ continue
65
+ n = a.get("name", "?")
66
+ d = a.get("description", "")
67
+ parts.append(f"- **`{n}`** — {d}")
68
+ return "\n".join(parts)
69
+
70
+
71
+ def _action_choices(info: dict) -> tuple[list[str], str | None]:
72
+ actions = [a for a in (info.get("available_actions") or []) if isinstance(a, dict)]
73
+ names = [a.get("name", "") for a in actions if a.get("name")]
74
+ if not names:
75
+ return [], None
76
+ return names, names[0]
77
+
78
+
79
+ def make_demo() -> gr.Blocks:
80
+ # Note: theme/css are passed at `launch()` when running standalone; here we use `mount_gradio_app`.
81
+ with gr.Blocks(title="Shin-chan life simulator") as demo:
82
+ gr.Markdown(
83
+ "# Shin-chan life simulator\n"
84
+ "Load a new episode, **choose an action** from the list (or random), and see "
85
+ "**reward** + what happened. Same rules as the API / OpenEnv server."
86
+ )
87
+ with gr.Row():
88
+ with gr.Column(scale=1, min_width=320):
89
+ new_ep = gr.Button("New episode", variant="primary", size="lg")
90
+ use_random = gr.Checkbox(
91
+ label="Random action (ignore choice below)", value=False
92
+ )
93
+ action_dd = gr.Dropdown(
94
+ label="Action",
95
+ choices=[],
96
+ value=None,
97
+ allow_custom_value=True,
98
+ info="List refreshes every time you start an episode or finish a non-terminal step.",
99
+ )
100
+ reason_in = gr.Textbox(
101
+ label="Reasoning (why this choice?)",
102
+ value="I want to be funny but not hurt anyone.",
103
+ lines=2,
104
+ )
105
+ line_in = gr.Textbox(
106
+ label="Dialogue (in character)",
107
+ value="Buri buri~ leave it to Shin-chan!",
108
+ lines=2,
109
+ )
110
+ go = gr.Button("Take this action", variant="primary")
111
+ with gr.Column(scale=1, min_width=320):
112
+ state_md = gr.Markdown("Click **New episode** to load a story.")
113
+ out = gr.Json(label="Last response (raw JSON)")
114
+
115
+ def on_new():
116
+ env = _get_env()
117
+ env.reset(seed=None)
118
+ info_obs = env.step(
119
+ CallToolAction(tool_name="get_scenario_info", arguments={})
120
+ )
121
+ info = _obs_result(info_obs)
122
+ choices, value = _action_choices(info)
123
+ j = {
124
+ "ok": True,
125
+ "get_scenario_info": info,
126
+ }
127
+ if not info or (not info.get("title") and not info.get("available_actions")):
128
+ j["warning"] = (
129
+ "Parsed scenario is empty; if this persists, check server logs for MCP observation shape."
130
+ )
131
+ return (
132
+ _fmt_state(info),
133
+ gr.update(choices=choices, value=value),
134
+ j,
135
+ )
136
+
137
+ def on_action(
138
+ random_pick: bool, aname: str | None, rtxt: str, dtxt: str, current_state: str
139
+ ):
140
+ env = _get_env()
141
+ info_obs = env.step(
142
+ CallToolAction(tool_name="get_scenario_info", arguments={})
143
+ )
144
+ info = _obs_result(info_obs)
145
+ actions = info.get("available_actions") or []
146
+ if not actions:
147
+ return {
148
+ "error": "No scenario loaded. Click **New episode** first.",
149
+ }, current_state, gr.update()
150
+
151
+ names = [a.get("name") for a in actions if isinstance(a, dict) and a.get("name")]
152
+ if random_pick and names:
153
+ aname = str(random.choice(names))
154
+ aname = (aname or "").strip()
155
+ if not aname:
156
+ return {
157
+ "error": "Choose an action from the list or enable **Random action**.",
158
+ }, current_state, gr.update()
159
+
160
+ if names and aname not in names:
161
+ return {
162
+ "error": f"Invalid action {aname!r}. Use one of: {names}",
163
+ }, current_state, gr.update()
164
+
165
+ step_obs = env.step(
166
+ CallToolAction(
167
+ tool_name="choose_action",
168
+ arguments={
169
+ "action_name": aname,
170
+ "reasoning": rtxt or "—",
171
+ "dialogue": dtxt or "—",
172
+ },
173
+ )
174
+ )
175
+ res = _obs_result(step_obs)
176
+ payload = {
177
+ "action_name": aname,
178
+ "reward": float(getattr(step_obs, "reward", 0.0) or 0.0),
179
+ "done": bool(getattr(step_obs, "done", False)),
180
+ "result": res,
181
+ }
182
+
183
+ if getattr(step_obs, "done", False):
184
+ return (
185
+ payload,
186
+ _fmt_state(info)
187
+ + "\n\n---\n\n**Episode finished.** Start a **New episode** to play again.",
188
+ gr.update(),
189
+ )
190
+
191
+ next_obs = env.step(
192
+ CallToolAction(tool_name="get_scenario_info", arguments={})
193
+ )
194
+ ninfo = _obs_result(next_obs)
195
+ choices, value = _action_choices(ninfo)
196
+ return (
197
+ payload,
198
+ _fmt_state(ninfo),
199
+ gr.update(choices=choices, value=value),
200
+ )
201
+
202
+ new_ep.click(
203
+ on_new,
204
+ outputs=[state_md, action_dd, out],
205
+ )
206
+ go.click(
207
+ on_action,
208
+ inputs=[use_random, action_dd, reason_in, line_in, state_md],
209
+ outputs=[out, state_md, action_dd],
210
+ )
211
+
212
+ return demo
server/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ openenv-core[core]>=0.2.2
2
+ fastapi>=0.115.0
3
+ pydantic>=2.0.0
4
+ uvicorn>=0.24.0
5
+ requests>=2.31.0
6
+ fastmcp>=0.1.0
7
+ gradio>=4.0.0
server/reward_engine.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ Reward Engine for ShinChan Life Simulator.
6
+
7
+ Calculates multi-dimensional rewards based on:
8
+ 1. Decision Quality (did they pick the optimal actions?)
9
+ 2. Social Awareness (did they consider others' feelings?)
10
+ 3. Personality Preservation (did they stay in character?)
11
+ 4. Responsibility
12
+ 5. Relationship Impact
13
+ 6. Long-Term Thinking
14
+ 7. Creativity
15
+ """
16
+
17
+ from .scenarios import Scenario
18
+ from .characters import get_character
19
+
20
+ # Common Shin-chan catchphrases and keywords
21
+ SHINCHAN_KEYWORDS = [
22
+ "buri buri", "action kamen", "chocobi", "ore wa", "ora",
23
+ "pretty lady", "miss yoshinaga", "butt", "dance", "hey hey",
24
+ "wahaha", "shinnosuke", "himawari", "shiro"
25
+ ]
26
+
27
+ def evaluate_action(
28
+ scenario: Scenario,
29
+ step_num: int,
30
+ action_name: str,
31
+ reasoning: str,
32
+ dialogue: str,
33
+ action_history: list[str],
34
+ dialogue_history: list[str] | None = None,
35
+ ) -> dict[str, float]:
36
+ """
37
+ Evaluates a single action and returns reward components.
38
+
39
+ Returns:
40
+ dict containing individual scores and the 'total' reward.
41
+ """
42
+ scores = {
43
+ "decision_quality": 0.0,
44
+ "social_awareness": 0.0,
45
+ "reasoning_quality": 0.0,
46
+ "personality": 0.0,
47
+ "responsibility": 0.0,
48
+ "relationship_impact": 0.0,
49
+ "long_term_thinking": 0.0,
50
+ "creativity": 0.0,
51
+ "repetition_penalty": 0.0,
52
+ "reasoning_penalty": 0.0,
53
+ "dialogue_repetition_penalty": 0.0,
54
+ "total": 0.0
55
+ }
56
+
57
+ action_def = scenario.get_action_by_name(action_name)
58
+ if not action_def:
59
+ # Invalid action penalty
60
+ scores["total"] = -0.5
61
+ return scores
62
+
63
+ tags = action_def.get("tags", [])
64
+
65
+ # 1. Decision Quality (0.0 to 1.0)
66
+ # Check if action aligns with the optimal path
67
+ is_optimal = False
68
+ if step_num < len(scenario.optimal_path):
69
+ expected_action = scenario.optimal_path[step_num]
70
+ if action_name == expected_action:
71
+ scores["decision_quality"] = 1.0
72
+ is_optimal = True
73
+ elif action_name in scenario.optimal_path:
74
+ scores["decision_quality"] = 0.5 # Right idea, wrong order
75
+
76
+ # Penalize clearly bad tags if not optimal
77
+ if not is_optimal:
78
+ bad_tags = ["selfish", "mean", "bullying", "dangerous", "ignoring_duties", "stealing"]
79
+ good_tags = ["responsible", "sharing", "honest", "brave", "caring"]
80
+
81
+ if any(tag in bad_tags for tag in tags):
82
+ scores["decision_quality"] -= 0.3
83
+ if any(tag in good_tags for tag in tags):
84
+ scores["decision_quality"] += 0.4
85
+
86
+ # Ensure bounds
87
+ scores["decision_quality"] = max(0.0, min(1.0, scores["decision_quality"]))
88
+
89
+ # 2. Social Awareness (0.0 to 1.0)
90
+ # Does the reasoning mention the characters involved?
91
+ reasoning_lower = reasoning.lower()
92
+ mentioned_chars = 0
93
+ for char_id in scenario.characters_involved:
94
+ char = get_character(char_id)
95
+ if char:
96
+ # Check for name or roles (mom, dad)
97
+ if char.name.lower().split()[0] in reasoning_lower or char_id in reasoning_lower:
98
+ mentioned_chars += 1
99
+ elif char_id == "misae" and "mom" in reasoning_lower:
100
+ mentioned_chars += 1
101
+ elif char_id == "hiroshi" and "dad" in reasoning_lower:
102
+ mentioned_chars += 1
103
+
104
+ if scenario.characters_involved:
105
+ scores["social_awareness"] = min(1.0, mentioned_chars / len(scenario.characters_involved))
106
+ # Bonus if they mention feelings or consequences
107
+ if any(word in reasoning_lower for word in ["sad", "angry", "happy", "cry", "feel", "because", "would"]):
108
+ scores["social_awareness"] = min(1.0, scores["social_awareness"] + 0.3)
109
+ if any(word in reasoning_lower for word in ["if", "then", "so that", "consequence", "later", "tomorrow"]):
110
+ scores["social_awareness"] = min(1.0, scores["social_awareness"] + 0.1)
111
+ else:
112
+ scores["social_awareness"] = 0.5 # Default if no chars involved
113
+
114
+ # 3. Reasoning Quality (0.0 to 1.0)
115
+ # Reward non-generic, consequence-aware explanations.
116
+ reasoning_stripped = reasoning.strip()
117
+ generic_patterns = [
118
+ "i should be good",
119
+ "this is best",
120
+ "because it is good",
121
+ "it's the right thing",
122
+ "just because",
123
+ ]
124
+ causal_markers = ["because", "if", "then", "so that", "otherwise", "consequence", "later", "tomorrow"]
125
+ if len(reasoning_stripped) >= 20:
126
+ scores["reasoning_quality"] += 0.4
127
+ if len(reasoning_stripped.split()) >= 8:
128
+ scores["reasoning_quality"] += 0.2
129
+ if any(marker in reasoning_lower for marker in causal_markers):
130
+ scores["reasoning_quality"] += 0.3
131
+ if mentioned_chars > 0:
132
+ scores["reasoning_quality"] += 0.2
133
+ scores["reasoning_quality"] = max(0.0, min(1.0, scores["reasoning_quality"]))
134
+
135
+ # Penalize empty/generic reasoning to reduce reward hacking.
136
+ if len(reasoning_stripped) < 12:
137
+ scores["reasoning_penalty"] = -0.12
138
+ elif any(pat in reasoning_lower for pat in generic_patterns):
139
+ scores["reasoning_penalty"] = -0.08
140
+
141
+ # 4. Personality Preservation (0.0 to 1.0)
142
+ # Does the dialogue sound like Shin-chan?
143
+ dialogue_lower = dialogue.lower()
144
+ keyword_count = sum(1 for kw in SHINCHAN_KEYWORDS if kw in dialogue_lower)
145
+
146
+ if keyword_count >= 2:
147
+ scores["personality"] = 1.0
148
+ elif keyword_count == 1:
149
+ scores["personality"] = 0.7
150
+ else:
151
+ # Check for informal/childish language style vs robotic AI
152
+ if "I will now proceed to" in dialogue or "As an AI" in dialogue:
153
+ scores["personality"] = 0.0
154
+ elif len(dialogue) < 10: # Too short
155
+ scores["personality"] = 0.3
156
+ else:
157
+ scores["personality"] = 0.5
158
+
159
+ # 5. Responsibility (0.0 to 1.0)
160
+ if any(tag in tags for tag in ["responsible", "doing_homework", "caring_for_himawari", "caring_for_shiro", "studying"]):
161
+ scores["responsibility"] += 0.8
162
+ if any(tag in tags for tag in ["ignoring_duties", "lazy", "disobedient", "selfish"]):
163
+ scores["responsibility"] -= 0.4
164
+ scores["responsibility"] = max(0.0, min(1.0, scores["responsibility"]))
165
+
166
+ # 6. Relationship Impact (-0.5 to 0.5)
167
+ scenario_impact = scenario.stakeholder_impacts.get(action_name, {}) if scenario.stakeholder_impacts else {}
168
+ if scenario_impact:
169
+ avg_impact = sum(scenario_impact.values()) / max(len(scenario_impact), 1)
170
+ scores["relationship_impact"] = max(-0.5, min(0.5, avg_impact))
171
+ else:
172
+ if any(tag in tags for tag in ["sharing", "helpful", "teamwork", "caring"]):
173
+ scores["relationship_impact"] += 0.15
174
+ if any(tag in tags for tag in ["mean", "bullying", "lying", "stealing", "selfish"]):
175
+ scores["relationship_impact"] -= 0.15
176
+ scores["relationship_impact"] = max(-0.5, min(0.5, scores["relationship_impact"]))
177
+
178
+ # 7. Long-Term Thinking (0.0 to 0.5)
179
+ if any(word in reasoning_lower for word in ["tomorrow", "later", "future", "consequence", "if", "so that"]):
180
+ scores["long_term_thinking"] = 0.5
181
+ elif any(word in reasoning_lower for word in ["next", "after", "then"]):
182
+ scores["long_term_thinking"] = 0.3
183
+
184
+ # 8. Creativity (0.0 to 0.5)
185
+ if any(tag in tags for tag in ["funny", "distracting", "peacemaker", "smart"]):
186
+ scores["creativity"] = 0.4
187
+ if action_name not in scenario.optimal_path and scores["decision_quality"] > 0.3:
188
+ scores["creativity"] = min(0.5, scores["creativity"] + 0.1)
189
+
190
+ # Anti-gaming: repeated identical action choice over recent history.
191
+ if len(action_history) >= 3 and len(set(action_history[-3:])) == 1:
192
+ scores["repetition_penalty"] = -0.15
193
+
194
+ # Anti-gaming: repeated template dialogue over recent turns.
195
+ if dialogue_history:
196
+ normalized = dialogue_lower.strip()
197
+ recent_normalized = [d.lower().strip() for d in dialogue_history[-2:] if isinstance(d, str)]
198
+ if normalized and normalized in recent_normalized:
199
+ scores["dialogue_repetition_penalty"] = -0.10
200
+ if any(template in dialogue_lower for template in ["i will do my best", "okay i will do it", "fine i will do it"]):
201
+ scores["dialogue_repetition_penalty"] = min(
202
+ -0.05, scores["dialogue_repetition_penalty"]
203
+ )
204
+
205
+ # Combine scores with weights
206
+ weights = {
207
+ "decision_quality": 0.28,
208
+ "social_awareness": 0.19,
209
+ "reasoning_quality": 0.09,
210
+ "personality": 0.15,
211
+ "responsibility": 0.15,
212
+ "creativity": 0.08,
213
+ "long_term_thinking": 0.06,
214
+ "relationship_impact": 0.05,
215
+ }
216
+
217
+ scores["total"] = (
218
+ scores["decision_quality"] * weights["decision_quality"] +
219
+ scores["social_awareness"] * weights["social_awareness"] +
220
+ scores["reasoning_quality"] * weights["reasoning_quality"] +
221
+ scores["personality"] * weights["personality"] +
222
+ scores["responsibility"] * weights["responsibility"] +
223
+ scores["creativity"] * weights["creativity"] +
224
+ scores["long_term_thinking"] * weights["long_term_thinking"] +
225
+ scores["relationship_impact"] * weights["relationship_impact"] +
226
+ scores["repetition_penalty"] +
227
+ scores["reasoning_penalty"] +
228
+ scores["dialogue_repetition_penalty"]
229
+ )
230
+
231
+ scores["total"] = max(-0.5, min(1.0, scores["total"]))
232
+
233
+ return scores
server/scenario_data.py ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ Scenario database for ShinChan Life Simulator.
6
+ Contains a diverse set of life situations categorized by difficulty.
7
+ """
8
+
9
+ from .scenarios import Scenario
10
+
11
+ # Helper for common action definitions to reduce boilerplate
12
+ def _action(name: str, desc: str, tags: list[str]) -> dict:
13
+ return {"name": name, "description": desc, "tags": tags}
14
+
15
+ ALL_SCENARIOS = [
16
+ # ---------------------------------------------------------
17
+ # PHASE 1: EASY SCENARIOS (Difficulty 1-2)
18
+ # ---------------------------------------------------------
19
+ Scenario(
20
+ id="easy_chocobi_001",
21
+ title="The Last Chocobi",
22
+ category="temptation",
23
+ difficulty=1,
24
+ narrative=(
25
+ "You just found the very last box of Chocobi in the cupboard! "
26
+ "You love Chocobi more than anything. But Himawari is napping "
27
+ "nearby, and Mom promised you'd share the next box with her."
28
+ ),
29
+ characters_involved=["misae", "himawari"],
30
+ available_actions=[
31
+ _action("eat_all", "Eat the whole box quietly before anyone sees", ["sneaking", "selfish"]),
32
+ _action("save_half", "Eat half and leave half for Himawari", ["sharing", "caring_for_himawari", "responsible"]),
33
+ _action("wake_himawari", "Wake Himawari up to eat together now", ["sharing", "disobedient", "annoying"]),
34
+ _action("hide_box", "Hide the box in your toy chest for later", ["sneaking", "selfish", "lying"]),
35
+ ],
36
+ optimal_path=["save_half"],
37
+ max_steps=1,
38
+ personality_context="Shin-chan loves Chocobi and usually has no self-control, but he does care about his sister deep down.",
39
+ stakeholder_impacts={
40
+ "eat_all": {"misae": -0.2, "himawari": -0.3},
41
+ "save_half": {"misae": 0.2, "himawari": 0.2},
42
+ }
43
+ ),
44
+ Scenario(
45
+ id="easy_clean_room_002",
46
+ title="Action Kamen vs Cleaning",
47
+ category="responsibility",
48
+ difficulty=1,
49
+ narrative=(
50
+ "Mom just yelled: 'SHIN-CHAN! Clean your toys right now!' "
51
+ "But the new episode of Action Kamen is starting on TV in 2 minutes. "
52
+ "If you miss it, you won't know how Action Kamen defeats the bad guy!"
53
+ ),
54
+ characters_involved=["misae"],
55
+ available_actions=[
56
+ _action("watch_tv", "Ignore Mom and watch Action Kamen", ["disobedient", "lazy", "ignoring_duties"]),
57
+ _action("clean_fast", "Quickly shove all toys under the bed and run to the TV", ["sneaking", "lazy"]),
58
+ _action("negotiate", "Ask Mom if you can clean AFTER the show ends", ["polite", "honest"]),
59
+ _action("clean_properly", "Clean up properly and miss the beginning of the show", ["responsible", "obedient"]),
60
+ ],
61
+ optimal_path=["negotiate", "clean_properly"],
62
+ max_steps=2,
63
+ personality_context="Shin-chan's top priority is always Action Kamen. Cleaning is his least favorite thing.",
64
+ stakeholder_impacts={}
65
+ ),
66
+ Scenario(
67
+ id="easy_dog_food_003",
68
+ title="Hungry Shiro",
69
+ category="responsibility",
70
+ difficulty=2,
71
+ narrative=(
72
+ "You're playing video games. You hear Shiro whimpering outside. "
73
+ "You remember you forgot to feed him his dinner, and Mom is busy cooking."
74
+ ),
75
+ characters_involved=["shiro", "misae"],
76
+ available_actions=[
77
+ _action("ignore", "Keep playing the game, Mom will do it later", ["lazy", "selfish"]),
78
+ _action("feed_shiro", "Pause the game and go feed Shiro", ["responsible", "caring_for_shiro"]),
79
+ _action("feed_snacks", "Throw some of your human snacks out the window for him", ["lazy", "bad_idea"]),
80
+ ],
81
+ optimal_path=["feed_shiro"],
82
+ max_steps=1,
83
+ personality_context="Shin-chan often forgets to feed Shiro, but he loves him.",
84
+ stakeholder_impacts={}
85
+ ),
86
+
87
+ # ---------------------------------------------------------
88
+ # PHASE 2: MEDIUM SCENARIOS (Difficulty 3)
89
+ # ---------------------------------------------------------
90
+ Scenario(
91
+ id="med_homework_lie_010",
92
+ title="The Homework Dilemma",
93
+ category="school",
94
+ difficulty=3,
95
+ narrative=(
96
+ "It's Sunday evening. Misae storms in. 'SHIN-CHAN! Did you finish your homework?!' "
97
+ "Your notebook is completely blank. Kazama just texted asking if you want to play outside. "
98
+ "The homework is 3 pages of math due tomorrow."
99
+ ),
100
+ characters_involved=["misae", "kazama"],
101
+ available_actions=[
102
+ _action("lie_homework", "Tell Mom you finished it at school", ["lying", "sneaking"]),
103
+ _action("go_play", "Sneak out the window to play with Kazama", ["sneaking", "disobedient"]),
104
+ _action("confess_and_do", "Tell the truth and start doing it", ["honest", "doing_homework", "responsible"]),
105
+ _action("ask_kazama_help", "Ask Kazama to come over and help you instead of playing", ["honest", "studying", "teamwork"]),
106
+ ],
107
+ optimal_path=["ask_kazama_help"],
108
+ max_steps=2,
109
+ personality_context="Shin-chan hates math and loves playing, but Kazama is a good influence if utilized well.",
110
+ stakeholder_impacts={}
111
+ ),
112
+ Scenario(
113
+ id="med_friend_fight_011",
114
+ title="Nene's Tears",
115
+ category="social",
116
+ difficulty=3,
117
+ narrative=(
118
+ "You and the gang are at the park. Masao accidentally stepped on Nene's favorite stuffed rabbit "
119
+ "and got mud on it. Nene is furious and is about to punch Masao. Masao is crying."
120
+ ),
121
+ characters_involved=["nene", "masao"],
122
+ available_actions=[
123
+ _action("laugh", "Laugh at Masao for crying", ["mean", "bullying"]),
124
+ _action("join_nene", "Help Nene yell at Masao", ["mean", "bullying"]),
125
+ _action("defend_masao", "Stand between them and tell Nene it was an accident", ["brave", "protecting_others"]),
126
+ _action("distract", "Drop your pants and do the alien dance to distract them", ["embarrassing", "funny", "peacemaker"]),
127
+ _action("clean_rabbit", "Take the rabbit and try to wipe the mud off", ["helpful", "caring"]),
128
+ ],
129
+ optimal_path=["distract", "clean_rabbit"],
130
+ max_steps=2,
131
+ personality_context="Shin-chan usually makes inappropriate jokes to diffuse tension, which surprisingly works.",
132
+ stakeholder_impacts={}
133
+ ),
134
+ Scenario(
135
+ id="med_dad_wallet_012",
136
+ title="Dad's Secret Stash",
137
+ category="family",
138
+ difficulty=3,
139
+ narrative=(
140
+ "While looking for a toy under the sofa, you find an envelope with ¥5,000 in it. "
141
+ "It has Dad's handwriting on it saying 'Secret Beer Fund'. Mom has been complaining "
142
+ "about being tight on money this month."
143
+ ),
144
+ characters_involved=["hiroshi", "misae"],
145
+ available_actions=[
146
+ _action("take_money", "Take the money to buy Chocobi and Action Kamen toys", ["stealing", "selfish", "wasting_money"]),
147
+ _action("tell_mom", "Give it to Mom immediately", ["honest", "betraying_dad"]),
148
+ _action("blackmail_dad", "Tell Dad you found it and demand a bribe to keep quiet", ["sneaking", "funny", "naughty"]),
149
+ _action("leave_it", "Put it back where you found it", ["neutral", "respectful"]),
150
+ ],
151
+ optimal_path=["blackmail_dad", "leave_it"], # A very Shin-chan path
152
+ max_steps=2,
153
+ personality_context="Shin-chan loves exploiting his parents' secrets for snacks, but won't cause serious family drama.",
154
+ stakeholder_impacts={}
155
+ ),
156
+
157
+ # ---------------------------------------------------------
158
+ # PHASE 3: HARD SCENARIOS (Difficulty 4-5)
159
+ # ---------------------------------------------------------
160
+ Scenario(
161
+ id="hard_sick_mom_020",
162
+ title="Misae is Down",
163
+ category="responsibility",
164
+ difficulty=4,
165
+ narrative=(
166
+ "Mom has a high fever and is sleeping in the bedroom. Dad is stuck at work late. "
167
+ "Himawari is awake and starting to get hungry and fussy. The house is a mess, "
168
+ "and your own stomach is rumbling."
169
+ ),
170
+ characters_involved=["misae", "himawari", "hiroshi"],
171
+ available_actions=[
172
+ _action("wake_mom", "Wake Mom up and complain you are hungry", ["selfish", "annoying"]),
173
+ _action("feed_himawari", "Find baby food and try to feed Himawari yourself", ["responsible", "caring_for_himawari"]),
174
+ _action("call_dad", "Call Dad at work and tell him to come home", ["helpful", "smart"]),
175
+ _action("cook_dinner", "Try to use the stove to cook something", ["dangerous", "well_intentioned"]),
176
+ _action("make_cold_dinner", "Get bread and milk for you and Himawari", ["smart", "responsible", "safe"]),
177
+ ],
178
+ optimal_path=["feed_himawari", "make_cold_dinner"],
179
+ max_steps=3,
180
+ personality_context="When things get truly serious, Shin-chan drops the silly act and becomes a surprisingly reliable big brother.",
181
+ stakeholder_impacts={}
182
+ ),
183
+ Scenario(
184
+ id="hard_bully_confrontation_021",
185
+ title="The Older Kids",
186
+ category="social",
187
+ difficulty=5,
188
+ narrative=(
189
+ "You and Kazama are walking home. Three older boys corner Kazama and demand his limited-edition "
190
+ "Moe-P trading card. Kazama is terrified but refuses. The biggest boy grabs Kazama by the shirt."
191
+ ),
192
+ characters_involved=["kazama"],
193
+ available_actions=[
194
+ _action("run_away", "Run away to save yourself", ["cowardly", "selfish"]),
195
+ _action("fight", "Try to punch the big kid", ["brave", "dangerous"]),
196
+ _action("yell_for_adult", "Scream loudly for a grown-up", ["smart", "safe"]),
197
+ _action("bizarre_intimidation", "Do the 'butt dance' and act completely insane to confuse them", ["brave", "funny", "distracting", "embarrassing"]),
198
+ _action("offer_trade", "Offer them your half-eaten Chocobi instead", ["funny", "peaceful"]),
199
+ ],
200
+ optimal_path=["bizarre_intimidation", "yell_for_adult"],
201
+ max_steps=3,
202
+ personality_context="Shin-chan's greatest weapon against bullies is his sheer unpredictability and lack of shame.",
203
+ stakeholder_impacts={}
204
+ ),
205
+ Scenario(
206
+ id="easy_share_toy_004",
207
+ title="Kazama Wants Your Robot",
208
+ category="social",
209
+ difficulty=2,
210
+ narrative=(
211
+ "Kazama wants to borrow your favorite Action Kamen robot for one day. "
212
+ "You are scared he might scratch it, but he promises to be careful."
213
+ ),
214
+ characters_involved=["kazama"],
215
+ available_actions=[
216
+ _action("refuse_rudely", "Refuse and call Kazama a boring rich kid", ["being_rude", "mean"]),
217
+ _action("lend_with_rule", "Lend it but ask him to return it by evening", ["sharing", "responsible", "teamwork"]),
218
+ _action("trade_for_snacks", "Lend it only if he gives you Chocobi", ["funny", "negotiation"]),
219
+ _action("hide_robot", "Hide it and pretend you lost it", ["lying", "sneaking"]),
220
+ ],
221
+ optimal_path=["lend_with_rule"],
222
+ max_steps=1,
223
+ personality_context="Shin-chan can be possessive, but he values friendship and can negotiate in his own style.",
224
+ stakeholder_impacts={
225
+ "lend_with_rule": {"kazama": 0.2},
226
+ "refuse_rudely": {"kazama": -0.2},
227
+ }
228
+ ),
229
+ Scenario(
230
+ id="easy_blackboard_005",
231
+ title="Who Drew on the Blackboard?",
232
+ category="school",
233
+ difficulty=2,
234
+ narrative=(
235
+ "Yoshinaga-sensei sees a silly drawing on the blackboard before class. "
236
+ "You drew it for fun. She asks who did it."
237
+ ),
238
+ characters_involved=["yoshinaga"],
239
+ available_actions=[
240
+ _action("blame_friend", "Blame Masao before he speaks", ["lying", "mean"]),
241
+ _action("confess", "Admit it and apologize", ["honest", "apologizing", "responsible"]),
242
+ _action("joke_escape", "Make a joke and change topic", ["funny", "sneaking"]),
243
+ ],
244
+ optimal_path=["confess"],
245
+ max_steps=1,
246
+ personality_context="Shin-chan often jokes first, but honest confession gives the best long-term outcome.",
247
+ stakeholder_impacts={
248
+ "confess": {"yoshinaga": 0.2},
249
+ "blame_friend": {"yoshinaga": -0.2},
250
+ }
251
+ ),
252
+ Scenario(
253
+ id="easy_lunch_006",
254
+ title="Vegetable Lunch Crisis",
255
+ category="school",
256
+ difficulty=1,
257
+ narrative=(
258
+ "Mom packed carrots and broccoli in your lunch. You want fried chicken from Kazama's box."
259
+ ),
260
+ characters_involved=["misae", "kazama"],
261
+ available_actions=[
262
+ _action("throw_veggies", "Throw vegetables in the trash", ["wasting_food", "lying"]),
263
+ _action("trade_politely", "Ask Kazama for a fair trade", ["polite", "sharing", "teamwork"]),
264
+ _action("eat_then_reward", "Eat your vegetables first, then ask for one bite", ["responsible", "smart"]),
265
+ ],
266
+ optimal_path=["eat_then_reward"],
267
+ max_steps=1,
268
+ personality_context="Shin-chan dislikes vegetables but can be convinced by rewards.",
269
+ stakeholder_impacts={}
270
+ ),
271
+ Scenario(
272
+ id="easy_himawari_007",
273
+ title="Baby on Patrol",
274
+ category="family",
275
+ difficulty=2,
276
+ narrative=(
277
+ "Mom runs to answer a phone call and asks you to watch Himawari for five minutes. "
278
+ "Himawari crawls toward Dad's expensive camera."
279
+ ),
280
+ characters_involved=["misae", "himawari", "hiroshi"],
281
+ available_actions=[
282
+ _action("ignore_and_watch_tv", "Ignore and keep watching TV", ["ignoring_duties", "selfish"]),
283
+ _action("move_camera", "Move camera to safety and play with Himawari", ["responsible", "caring_for_himawari"]),
284
+ _action("scold_baby", "Shout at Himawari to stop", ["being_mean", "annoying"]),
285
+ ],
286
+ optimal_path=["move_camera"],
287
+ max_steps=1,
288
+ personality_context="Shin-chan is dramatic, but he does protect his sister in urgent moments.",
289
+ stakeholder_impacts={}
290
+ ),
291
+ Scenario(
292
+ id="easy_found_coin_008",
293
+ title="The 100 Yen Mystery",
294
+ category="family",
295
+ difficulty=2,
296
+ narrative=(
297
+ "You find 100 yen near the front door. No one is nearby. Chocobi is calling your name."
298
+ ),
299
+ characters_involved=["misae", "hiroshi"],
300
+ available_actions=[
301
+ _action("buy_chocobi", "Spend it immediately on Chocobi", ["selfish", "wasting_money"]),
302
+ _action("ask_whose", "Ask Mom and Dad whose money it is", ["honest", "responsible"]),
303
+ _action("secret_stash", "Hide it in your drawer for later", ["sneaking", "lying"]),
304
+ ],
305
+ optimal_path=["ask_whose"],
306
+ max_steps=1,
307
+ personality_context="Shin-chan loves snacks, but this is a simple honesty test.",
308
+ stakeholder_impacts={}
309
+ ),
310
+ Scenario(
311
+ id="med_birthday_013",
312
+ title="Mom's Birthday Tomorrow",
313
+ category="family",
314
+ difficulty=3,
315
+ narrative=(
316
+ "Mom's birthday is tomorrow. You have 200 yen. You can buy snacks, make a card, or pretend you forgot."
317
+ ),
318
+ characters_involved=["misae", "hiroshi", "himawari"],
319
+ available_actions=[
320
+ _action("buy_snacks_for_self", "Buy Chocobi for yourself", ["selfish", "wasting_money"]),
321
+ _action("make_card", "Make a handmade card and help set dinner", ["caring", "helping_house", "responsible"]),
322
+ _action("ask_dad_plan", "Ask Dad to plan a surprise together", ["teamwork", "smart", "caring"]),
323
+ ],
324
+ optimal_path=["ask_dad_plan", "make_card"],
325
+ max_steps=2,
326
+ personality_context="Shin-chan may clown around, but family celebrations bring out his sweet side.",
327
+ stakeholder_impacts={}
328
+ ),
329
+ Scenario(
330
+ id="med_window_014",
331
+ title="Neighbor's Window",
332
+ category="responsibility",
333
+ difficulty=3,
334
+ narrative=(
335
+ "Your ball broke the neighbor's window. Nobody saw it happen. The neighbor comes out looking confused."
336
+ ),
337
+ characters_involved=["misae", "hiroshi"],
338
+ available_actions=[
339
+ _action("run_hide", "Run and hide behind the fence", ["sneaking", "lying", "cowardly"]),
340
+ _action("confess_and_apologize", "Tell the truth and apologize", ["honest", "apologizing", "responsible"]),
341
+ _action("blame_cat", "Say a cat did it", ["lying", "funny"]),
342
+ ],
343
+ optimal_path=["confess_and_apologize"],
344
+ max_steps=1,
345
+ personality_context="Shin-chan can invent wild excuses, but accountability is the growth path.",
346
+ stakeholder_impacts={}
347
+ ),
348
+ Scenario(
349
+ id="med_copy_homework_015",
350
+ title="Copy My Homework, Please",
351
+ category="school",
352
+ difficulty=3,
353
+ narrative=(
354
+ "Masao begs you to let him copy your worksheet. Teacher will collect them in ten minutes."
355
+ ),
356
+ characters_involved=["masao", "yoshinaga"],
357
+ available_actions=[
358
+ _action("let_copy", "Let Masao copy everything", ["cheating", "being_lazy"]),
359
+ _action("teach_quick", "Help him solve two key questions quickly", ["helpful", "studying", "teamwork"]),
360
+ _action("report_masao", "Tell teacher Masao is asking to cheat", ["honest", "being_mean"]),
361
+ ],
362
+ optimal_path=["teach_quick"],
363
+ max_steps=1,
364
+ personality_context="Shin-chan prefers shortcuts, but helping a friend learn is better than cheating.",
365
+ stakeholder_impacts={}
366
+ ),
367
+ Scenario(
368
+ id="med_secret_016",
369
+ title="Masao's Secret",
370
+ category="social",
371
+ difficulty=3,
372
+ narrative=(
373
+ "You accidentally told Nene that Masao is afraid of ghost stories. "
374
+ "Masao is upset and won't talk to you."
375
+ ),
376
+ characters_involved=["masao", "nene"],
377
+ available_actions=[
378
+ _action("deny_it", "Pretend you never said it", ["lying", "sneaking"]),
379
+ _action("apologize_private", "Apologize to Masao and promise to protect his secret", ["honest", "apologizing", "caring"]),
380
+ _action("make_joke", "Turn it into a comedy routine", ["funny", "embarrassing"]),
381
+ ],
382
+ optimal_path=["apologize_private"],
383
+ max_steps=1,
384
+ personality_context="Shin-chan jokes a lot, but trust repair needs sincerity.",
385
+ stakeholder_impacts={}
386
+ ),
387
+ Scenario(
388
+ id="med_party_vs_study_017",
389
+ title="Promise vs Party",
390
+ category="social",
391
+ difficulty=3,
392
+ narrative=(
393
+ "You promised Kazama to study together today, but Nene's birthday party starts now. "
394
+ "Both are expecting you."
395
+ ),
396
+ characters_involved=["kazama", "nene"],
397
+ available_actions=[
398
+ _action("ghost_kazama", "Go to the party and ignore Kazama's messages", ["lying", "selfish"]),
399
+ _action("study_then_party", "Study first, then join party late with apology", ["responsible", "teamwork", "honest"]),
400
+ _action("skip_party", "Skip party and only study", ["responsible", "being_mean"]),
401
+ ],
402
+ optimal_path=["study_then_party"],
403
+ max_steps=2,
404
+ personality_context="Shin-chan can juggle both if he communicates honestly.",
405
+ stakeholder_impacts={}
406
+ ),
407
+ Scenario(
408
+ id="hard_stranger_022",
409
+ title="Candy from a Stranger",
410
+ category="social",
411
+ difficulty=5,
412
+ narrative=(
413
+ "A stranger offers you expensive candy and says he'll show you a secret Action Kamen set nearby."
414
+ ),
415
+ characters_involved=["misae", "hiroshi"],
416
+ available_actions=[
417
+ _action("follow_stranger", "Follow him quietly", ["dangerous", "selfish"]),
418
+ _action("shout_and_run_home", "Refuse loudly and run to a safe adult", ["brave", "safe", "smart"]),
419
+ _action("ask_for_more", "Try to negotiate for two candy boxes", ["funny", "dangerous"]),
420
+ ],
421
+ optimal_path=["shout_and_run_home"],
422
+ max_steps=1,
423
+ personality_context="Even silly Shin-chan must prioritize safety over temptation here.",
424
+ stakeholder_impacts={}
425
+ ),
426
+ Scenario(
427
+ id="hard_bad_score_023",
428
+ title="Report Card Panic",
429
+ category="school",
430
+ difficulty=4,
431
+ narrative=(
432
+ "You got a very low test score. Parent-teacher meeting is tomorrow. "
433
+ "You can hide the test, confess now, or ask for a study plan."
434
+ ),
435
+ characters_involved=["misae", "hiroshi", "yoshinaga"],
436
+ available_actions=[
437
+ _action("hide_test", "Hide the test paper", ["lying", "sneaking"]),
438
+ _action("confess_now", "Tell parents now and ask for help", ["honest", "studying", "responsible"]),
439
+ _action("forge_signature", "Fake Dad's signature", ["lying", "cheating", "dangerous"]),
440
+ ],
441
+ optimal_path=["confess_now"],
442
+ max_steps=1,
443
+ personality_context="Short-term escape is tempting, but long-term trust matters.",
444
+ stakeholder_impacts={}
445
+ ),
446
+ Scenario(
447
+ id="hard_parents_fight_024",
448
+ title="A Tense Dinner",
449
+ category="family",
450
+ difficulty=4,
451
+ narrative=(
452
+ "Mom and Dad are arguing about money at dinner. Himawari starts crying. "
453
+ "The room is tense and everyone is upset."
454
+ ),
455
+ characters_involved=["misae", "hiroshi", "himawari"],
456
+ available_actions=[
457
+ _action("make_it_worse", "Mock both of them with jokes", ["being_rude", "embarrassing"]),
458
+ _action("calm_himawari", "Take Himawari aside and distract her", ["caring_for_himawari", "responsible", "helpful"]),
459
+ _action("ask_break", "Ask both parents to pause and eat first", ["smart", "showing_empathy", "brave"]),
460
+ ],
461
+ optimal_path=["calm_himawari", "ask_break"],
462
+ max_steps=2,
463
+ personality_context="Shin-chan can defuse tension with humor, but empathy-first actions work best in this conflict.",
464
+ stakeholder_impacts={}
465
+ ),
466
+ Scenario(
467
+ id="hard_two_friends_025",
468
+ title="Pick a Side",
469
+ category="social",
470
+ difficulty=4,
471
+ narrative=(
472
+ "Kazama and Nene are fighting and both demand you support only them. "
473
+ "If you pick one harshly, the other may stop talking to you."
474
+ ),
475
+ characters_involved=["kazama", "nene"],
476
+ available_actions=[
477
+ _action("pick_kazama", "Choose Kazama and insult Nene", ["being_mean", "bullying"]),
478
+ _action("pick_nene", "Choose Nene and mock Kazama", ["being_mean", "bullying"]),
479
+ _action("mediate", "Hear both sides and propose a fair compromise", ["teamwork", "showing_empathy", "brave", "smart"]),
480
+ _action("escape", "Pretend stomach pain and run away", ["lying", "cowardly"]),
481
+ ],
482
+ optimal_path=["mediate"],
483
+ max_steps=1,
484
+ personality_context="Shin-chan's chaos can become diplomacy if he slows down and listens.",
485
+ stakeholder_impacts={}
486
+ ),
487
+ Scenario(
488
+ id="hard_move_city_026",
489
+ title="Moving Away",
490
+ category="family",
491
+ difficulty=5,
492
+ narrative=(
493
+ "Mom says the family might move to another city for Dad's work. "
494
+ "You do not want to leave your friends."
495
+ ),
496
+ characters_involved=["misae", "hiroshi", "kazama", "nene"],
497
+ available_actions=[
498
+ _action("tantrum", "Throw a huge tantrum and refuse everything", ["being_rude", "disobedient"]),
499
+ _action("talk_feelings", "Share feelings calmly and ask to stay in touch with friends", ["showing_empathy", "honest", "long_term"]),
500
+ _action("run_away", "Pack toys and run to the park", ["dangerous", "cowardly"]),
501
+ ],
502
+ optimal_path=["talk_feelings"],
503
+ max_steps=1,
504
+ personality_context="A hard emotional scenario where Shin-chan grows by expressing fear honestly.",
505
+ stakeholder_impacts={}
506
+ ),
507
+ Scenario(
508
+ id="hard_teacher_crying_027",
509
+ title="Teacher in Tears",
510
+ category="school",
511
+ difficulty=4,
512
+ narrative=(
513
+ "You spot Yoshinaga-sensei crying quietly in the staff room after class. "
514
+ "No other adult is nearby."
515
+ ),
516
+ characters_involved=["yoshinaga", "kazama"],
517
+ available_actions=[
518
+ _action("mock_crying", "Imitate crying to make a joke", ["being_rude", "embarrassing"]),
519
+ _action("silent_support", "Leave a kind note and call another teacher", ["showing_empathy", "smart", "helpful"]),
520
+ _action("tell_class", "Announce it to classmates for drama", ["lying", "being_mean"]),
521
+ ],
522
+ optimal_path=["silent_support"],
523
+ max_steps=1,
524
+ personality_context="Shin-chan can still be kind in adult emotional moments when guided by empathy.",
525
+ stakeholder_impacts={}
526
+ ),
527
+ Scenario(
528
+ id="easy_pocket_money_028",
529
+ title="Pocket Money Choice",
530
+ category="responsibility",
531
+ difficulty=2,
532
+ narrative=(
533
+ "Dad gives you Y300 pocket money for the week. On the way home, you see Chocobi, "
534
+ "a toy sticker set for Himawari, and a school donation box for a class event."
535
+ ),
536
+ characters_involved=["hiroshi", "himawari", "yoshinaga"],
537
+ available_actions=[
538
+ _action("buy_all_chocobi", "Spend everything on Chocobi today", ["selfish", "impulsive"]),
539
+ _action("split_money", "Buy one snack and save the rest", ["responsible", "long_term", "smart"]),
540
+ _action("gift_himawari", "Buy a small gift for Himawari and skip your snack", ["caring_for_himawari", "sharing"]),
541
+ _action("donate_all", "Donate all your money dramatically", ["helpful", "showing_empathy", "responsible"]),
542
+ ],
543
+ optimal_path=["split_money", "gift_himawari"],
544
+ max_steps=2,
545
+ personality_context="Shin-chan wants instant snacks, but can show surprising generosity with family.",
546
+ stakeholder_impacts={}
547
+ ),
548
+ Scenario(
549
+ id="easy_homework_friend_029",
550
+ title="Homework Copy Request",
551
+ category="school",
552
+ difficulty=2,
553
+ narrative=(
554
+ "Masao forgot his worksheet and whispers, 'Please let me copy yours before sensei checks!' "
555
+ "You know he is scared, and class starts in one minute."
556
+ ),
557
+ characters_involved=["masao", "yoshinaga"],
558
+ available_actions=[
559
+ _action("let_copy_fast", "Let Masao copy everything quickly", ["cheating", "being_nice"]),
560
+ _action("refuse_harsh", "Refuse and call him weak", ["being_mean", "bullying"]),
561
+ _action("help_explain", "Help him solve the first two questions now", ["teamwork", "helpful", "studying"]),
562
+ _action("tell_teacher", "Tell teacher he forgot and ask for partial credit", ["honest", "brave", "responsible"]),
563
+ ],
564
+ optimal_path=["help_explain", "tell_teacher"],
565
+ max_steps=2,
566
+ personality_context="Shin-chan can clown around but still support a nervous friend fairly.",
567
+ stakeholder_impacts={}
568
+ ),
569
+ Scenario(
570
+ id="med_birthday_budget_030",
571
+ title="Mom's Birthday Surprise",
572
+ category="family",
573
+ difficulty=3,
574
+ narrative=(
575
+ "Mom's birthday is tomorrow. You only have Y200 and Kazama suggests buying a tiny cake, "
576
+ "while Nene suggests making a handmade card and helping with chores."
577
+ ),
578
+ characters_involved=["misae", "kazama", "nene"],
579
+ available_actions=[
580
+ _action("buy_snacks_self", "Spend the money on your own snacks", ["selfish", "wasting_money"]),
581
+ _action("cheap_gift_only", "Buy a small gift but do nothing else", ["neutral", "caring"]),
582
+ _action("card_and_chores", "Make a card and clean the house before dinner", ["responsible", "showing_empathy", "helpful"]),
583
+ _action("ask_dad_plan", "Coordinate with Dad to combine your idea with his plan", ["teamwork", "smart", "long_term"]),
584
+ ],
585
+ optimal_path=["ask_dad_plan", "card_and_chores"],
586
+ max_steps=2,
587
+ personality_context="Shin-chan likes dramatic gestures, but thoughtful effort lands better than expensive gifts.",
588
+ stakeholder_impacts={}
589
+ ),
590
+ Scenario(
591
+ id="med_neighbor_window_031",
592
+ title="Broken Window Trouble",
593
+ category="social",
594
+ difficulty=3,
595
+ narrative=(
596
+ "Your ball broke the neighbor's window while playing with Bo. The neighbor is not home yet, "
597
+ "and Bo says maybe nobody saw it."
598
+ ),
599
+ characters_involved=["bo", "misae", "hiroshi"],
600
+ available_actions=[
601
+ _action("run_home_hide", "Run home and hide the ball", ["lying", "cowardly"]),
602
+ _action("blame_bo", "Say Bo kicked it", ["lying", "being_mean"]),
603
+ _action("wait_and_apologize", "Wait for neighbor and apologize honestly", ["honest", "brave", "responsible"]),
604
+ _action("call_parents_help", "Call your parents and ask how to fix it", ["smart", "helpful", "long_term"]),
605
+ ],
606
+ optimal_path=["call_parents_help", "wait_and_apologize"],
607
+ max_steps=2,
608
+ personality_context="This is classic Shin-chan chaos where honesty plus backup from adults is best.",
609
+ stakeholder_impacts={}
610
+ ),
611
+ Scenario(
612
+ id="med_babysit_chain_032",
613
+ title="Himawari Babysit Chain",
614
+ category="responsibility",
615
+ difficulty=3,
616
+ narrative=(
617
+ "Mom asks you to watch Himawari for 20 minutes while she talks to a delivery person. "
618
+ "At the same time, Action Kamen is starting and Shiro is barking at the door."
619
+ ),
620
+ characters_involved=["misae", "himawari", "shiro"],
621
+ available_actions=[
622
+ _action("watch_tv_ignore", "Watch TV and ignore both Himawari and Shiro", ["ignoring_duties", "selfish"]),
623
+ _action("secure_himawari", "Keep Himawari safe first, then check Shiro", ["caring_for_himawari", "responsible", "smart"]),
624
+ _action("take_himawari_tv", "Bring Himawari near TV and hope she stays calm", ["risky", "lazy"]),
625
+ _action("ask_mom_extension", "Ask Mom for one more minute to set things up safely", ["honest", "teamwork", "responsible"]),
626
+ ],
627
+ optimal_path=["ask_mom_extension", "secure_himawari"],
628
+ max_steps=2,
629
+ personality_context="Shin-chan can prioritize safety when it involves Himawari, even if he grumbles.",
630
+ stakeholder_impacts={}
631
+ ),
632
+ Scenario(
633
+ id="hard_exam_and_party_033",
634
+ title="Exam vs Birthday Party",
635
+ category="school",
636
+ difficulty=4,
637
+ narrative=(
638
+ "Big math exam tomorrow. Nene's birthday party is tonight at the same time Kazama planned a study group. "
639
+ "All three expect you to join them."
640
+ ),
641
+ characters_involved=["nene", "kazama", "misae"],
642
+ available_actions=[
643
+ _action("party_only", "Skip study and go all-in at party", ["ignoring_duties", "selfish"]),
644
+ _action("study_only", "Skip party completely and only study", ["responsible", "being_mean"]),
645
+ _action("split_plan", "Attend party briefly then join late study group", ["long_term", "teamwork", "smart"]),
646
+ _action("lie_to_both", "Tell each side you are with the other", ["lying", "sneaking"]),
647
+ ],
648
+ optimal_path=["split_plan"],
649
+ max_steps=1,
650
+ personality_context="Balanced compromise with clear communication is the growth path here.",
651
+ stakeholder_impacts={}
652
+ ),
653
+ Scenario(
654
+ id="hard_secret_spill_034",
655
+ title="Masao's Secret Leaked",
656
+ category="social",
657
+ difficulty=5,
658
+ narrative=(
659
+ "You accidentally told Nene about Masao's secret crush. Now Masao is crying and Nene is teasing him. "
660
+ "Everyone is staring at you to fix it."
661
+ ),
662
+ characters_involved=["masao", "nene", "kazama"],
663
+ available_actions=[
664
+ _action("deny_everything", "Deny saying anything and blame rumors", ["lying", "cowardly"]),
665
+ _action("apologize_public", "Apologize sincerely and ask everyone to stop teasing", ["honest", "showing_empathy", "brave"]),
666
+ _action("joke_escape", "Make a joke and run away", ["funny", "sneaking"]),
667
+ _action("repair_privately", "Talk to Masao privately and promise to rebuild trust", ["showing_empathy", "long_term", "responsible"]),
668
+ ],
669
+ optimal_path=["apologize_public", "repair_privately"],
670
+ max_steps=2,
671
+ personality_context="A hard trust-repair moment where comedic escape is tempting but accountability matters.",
672
+ stakeholder_impacts={}
673
+ ),
674
+ Scenario(
675
+ id="hard_formal_event_035",
676
+ title="Embarrassing Formal Event",
677
+ category="embarrassment",
678
+ difficulty=5,
679
+ narrative=(
680
+ "Your family attends Dad's office event. Mom warns you to behave politely. "
681
+ "A senior executive greets you, and everyone expects a respectful introduction."
682
+ ),
683
+ characters_involved=["misae", "hiroshi"],
684
+ available_actions=[
685
+ _action("butt_dance_now", "Do the elephant butt dance immediately", ["embarrassing", "disobedient"]),
686
+ _action("polite_intro", "Introduce yourself politely and thank them", ["responsible", "respectful"]),
687
+ _action("funny_but_clean", "Make one playful joke, then behave properly", ["funny", "smart", "long_term"]),
688
+ _action("hide_behind_mom", "Hide and refuse to speak", ["cowardly", "awkward"]),
689
+ ],
690
+ optimal_path=["funny_but_clean", "polite_intro"],
691
+ max_steps=2,
692
+ personality_context="The best version of Shin-chan is playful without crossing social boundaries.",
693
+ stakeholder_impacts={}
694
+ )
695
+ ]
server/scenarios.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ Scenario definitions and engine for the ShinChan Life Simulator.
6
+ """
7
+
8
+ from dataclasses import dataclass, field
9
+ import random
10
+
11
+
12
+ @dataclass
13
+ class Scenario:
14
+ """A single life scenario for Shin-chan to navigate."""
15
+
16
+ id: str # e.g., "school_homework_001"
17
+ title: str # e.g., "The Homework Dilemma"
18
+ category: str # school, family, social, temptation, responsibility
19
+ difficulty: int # 1 to 5
20
+ narrative: str # The setup story
21
+ characters_involved: list[str] # IDs of characters like "misae", "kazama"
22
+ available_actions: list[dict] # List of dicts: {"name": "action_id", "description": "text", "tags": [...]}
23
+ optimal_path: list[str] # Expected best sequence of action names
24
+ max_steps: int # How many steps the scenario lasts
25
+ personality_context: str # How Shin-chan typically acts here
26
+ stakeholder_impacts: dict # How different actions generally affect characters
27
+
28
+ def get_action_by_name(self, action_name: str) -> dict | None:
29
+ """Helper to find an action definition by its name."""
30
+ for action in self.available_actions:
31
+ if action["name"] == action_name:
32
+ return action
33
+ return None
34
+
35
+
36
+ class ScenarioEngine:
37
+ """Engine to manage and load scenarios."""
38
+
39
+ def __init__(self, scenarios: list[Scenario]):
40
+ self.scenarios = {s.id: s for s in scenarios}
41
+ self.scenarios_by_difficulty = {}
42
+ for s in scenarios:
43
+ if s.difficulty not in self.scenarios_by_difficulty:
44
+ self.scenarios_by_difficulty[s.difficulty] = []
45
+ self.scenarios_by_difficulty[s.difficulty].append(s)
46
+
47
+ def get_scenario(self, scenario_id: str) -> Scenario | None:
48
+ """Get a specific scenario by ID."""
49
+ return self.scenarios.get(scenario_id)
50
+
51
+ def get_random_scenario(self, max_difficulty: int = 5) -> Scenario:
52
+ """Get a random scenario up to a certain difficulty."""
53
+ valid_difficulties = [d for d in self.scenarios_by_difficulty.keys() if d <= max_difficulty]
54
+ if not valid_difficulties:
55
+ # Fallback if no easy scenarios exist (shouldn't happen)
56
+ return random.choice(list(self.scenarios.values()))
57
+
58
+ chosen_diff = random.choice(valid_difficulties)
59
+ return random.choice(self.scenarios_by_difficulty[chosen_diff])
60
+
61
+ def get_scenarios_for_phase(self, step_count: int) -> Scenario:
62
+ """
63
+ Graduated difficulty curve based on training steps.
64
+ Phase 1 (Steps 0-100): Easy (1-2)
65
+ Phase 2 (Steps 100-250): Medium (1-3)
66
+ Phase 3 (Steps 250-400): Hard (2-4)
67
+ Phase 4 (Steps 400+): All (1-5)
68
+ """
69
+ if step_count < 100:
70
+ return self.get_random_scenario(max_difficulty=2)
71
+ elif step_count < 250:
72
+ return self.get_random_scenario(max_difficulty=3)
73
+ elif step_count < 400:
74
+ # Try to pick from 2-4
75
+ valid_scenarios = [s for s in self.scenarios.values() if 2 <= s.difficulty <= 4]
76
+ return random.choice(valid_scenarios) if valid_scenarios else self.get_random_scenario(4)
77
+ else:
78
+ return self.get_random_scenario(max_difficulty=5)
server/sinchan_environment.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ # All rights reserved.
3
+
4
+ """
5
+ ShinChan Life Simulator Environment.
6
+
7
+ This is the main environment class that connects the MCP server to the scenario
8
+ engine, character simulation, and reward calculation.
9
+ """
10
+
11
+ from typing import Any, Optional
12
+ from uuid import uuid4
13
+
14
+ try:
15
+ from openenv.core.env_server.mcp_environment import MCPEnvironment
16
+ from openenv.core.env_server.types import Action, Observation, State
17
+ except ImportError:
18
+ from openenv.core.env_server.mcp_environment import MCPEnvironment
19
+ from openenv.core.env_server.types import Action, Observation, State
20
+
21
+ from fastmcp import FastMCP
22
+
23
+ from .scenario_data import ALL_SCENARIOS
24
+ from .scenarios import ScenarioEngine
25
+ from .characters import get_character
26
+ from .reward_engine import evaluate_action
27
+
28
+
29
+ class SinChanEnvironment(MCPEnvironment):
30
+ """
31
+ ShinChan Life Simulator Environment.
32
+
33
+ Exposes all interaction via FastMCP tools.
34
+ """
35
+
36
+ SUPPORTS_CONCURRENT_SESSIONS = True
37
+
38
+ def __init__(self):
39
+ """Initialize the environment with MCP server and tools."""
40
+ self.scenario_engine = ScenarioEngine(ALL_SCENARIOS)
41
+
42
+ # State tracking (will be reset per episode)
43
+ self.current_scenario = None
44
+ self.relationships = {}
45
+ self.action_history = []
46
+ self.episode_log = []
47
+ self.last_reward_info = {}
48
+
49
+ mcp = FastMCP("sinchan_env")
50
+
51
+ @mcp.tool
52
+ def new_episode(seed: Optional[int] = None) -> dict:
53
+ """
54
+ Start a new Shin-chan life scenario in this HTTP/WebSocket session.
55
+
56
+ Call this after openenv/session/create. (Plain POST /reset spins up a
57
+ throwaway environment and does not load a scenario for MCP tools.)
58
+ """
59
+ obs = self.reset(seed=seed)
60
+ meta = obs.metadata or {}
61
+ return {
62
+ "message": meta.get("message", "New scenario!"),
63
+ "hint": meta.get("hint", "Call get_scenario_info() to see the situation."),
64
+ }
65
+
66
+ @mcp.tool
67
+ def get_scenario_info() -> dict:
68
+ """
69
+ Get details about the current life situation Shin-chan is facing.
70
+ Call this first in a new episode!
71
+ """
72
+ if not self.current_scenario:
73
+ return {
74
+ "error": "No active scenario. Call new_episode() (or the gym reset) first.",
75
+ }
76
+
77
+ return {
78
+ "title": self.current_scenario.title,
79
+ "narrative": self.current_scenario.narrative,
80
+ "available_actions": [
81
+ {"name": a["name"], "description": a["description"]}
82
+ for a in self.current_scenario.available_actions
83
+ ],
84
+ "characters_involved": [
85
+ {"id": cid, "name": get_character(cid).name}
86
+ for cid in self.current_scenario.characters_involved if get_character(cid)
87
+ ]
88
+ }
89
+
90
+ @mcp.tool
91
+ def get_relationships() -> dict:
92
+ """
93
+ Check the current relationship status with all characters.
94
+ 0.0 = Hostile, 0.5 = Neutral, 1.0 = Best Friends.
95
+ """
96
+ if not self.relationships:
97
+ return {"status": "No relationship data available."}
98
+
99
+ return {
100
+ char_id: {"name": get_character(char_id).name, "value": round(val, 2)}
101
+ for char_id, val in self.relationships.items() if get_character(char_id)
102
+ }
103
+
104
+ @mcp.tool
105
+ def choose_action(action_name: str, reasoning: str, dialogue: str) -> dict:
106
+ """
107
+ Make a decision as Shin-chan in the current scenario.
108
+
109
+ Args:
110
+ action_name: The EXACT name of the action from available_actions (e.g. 'do_homework')
111
+ reasoning: Internal thought process (why choose this?)
112
+ dialogue: What Shin-chan says out loud (stay in character!)
113
+ """
114
+ if not self.current_scenario:
115
+ return {"error": "No active scenario."}
116
+
117
+ action_def = self.current_scenario.get_action_by_name(action_name)
118
+ if not action_def:
119
+ return {"error": f"Invalid action_name '{action_name}'. Check get_scenario_info()."}
120
+
121
+ # Process the action
122
+ self.action_history.append(action_name)
123
+ step_num = self._state.step_count
124
+
125
+ # 1. Calculate Rewards
126
+ reward_info = evaluate_action(
127
+ scenario=self.current_scenario,
128
+ step_num=step_num,
129
+ action_name=action_name,
130
+ reasoning=reasoning,
131
+ dialogue=dialogue,
132
+ action_history=self.action_history,
133
+ dialogue_history=[entry.get("dialogue", "") for entry in self.episode_log],
134
+ )
135
+ self.last_reward_info = reward_info
136
+
137
+ # 2. Get character reactions
138
+ reactions = []
139
+ for char_id in self.current_scenario.characters_involved:
140
+ char = get_character(char_id)
141
+ if char:
142
+ reaction_text, rel_change = char.get_reaction(action_name, action_def.get("tags", []))
143
+ if rel_change != 0.0:
144
+ self.relationships[char_id] = max(0.0, min(1.0, self.relationships.get(char_id, 0.5) + rel_change))
145
+ reactions.append(f"[{char.name}]: {reaction_text}")
146
+
147
+ # Log it
148
+ self.episode_log.append({
149
+ "action": action_name,
150
+ "dialogue": dialogue,
151
+ "reactions": reactions
152
+ })
153
+
154
+ # Compute done state from projected step after this action.
155
+ projected_steps = len(self.action_history)
156
+ done = bool(
157
+ self.current_scenario
158
+ and projected_steps >= self.current_scenario.max_steps
159
+ )
160
+
161
+ # Construct response with explicit reward/done for HTTP MCP clients.
162
+ response = {
163
+ "shinchan_said": dialogue,
164
+ "consequences": "\n".join(reactions) if reactions else "Nothing much happened.",
165
+ "reward": float(reward_info.get("total", 0.0)),
166
+ "reward_components": reward_info,
167
+ "done": done,
168
+ }
169
+
170
+ if done:
171
+ response["status"] = "Scenario complete! Call new_episode() for another chaos round."
172
+ else:
173
+ response["status"] = f"Step {len(self.action_history)}/{self.current_scenario.max_steps} complete. What's next?"
174
+
175
+ return response
176
+
177
+ # Pass MCP to base class
178
+ super().__init__(mcp)
179
+ self._state = State(episode_id=str(uuid4()), step_count=0)
180
+ self._total_episodes = 0
181
+
182
+ def reset(
183
+ self,
184
+ seed: Optional[int] = None,
185
+ episode_id: Optional[str] = None,
186
+ **kwargs: Any,
187
+ ) -> Observation:
188
+ """Reset the environment to a new scenario."""
189
+ if seed is not None:
190
+ import random
191
+ random.seed(seed)
192
+
193
+ self._total_episodes += 1
194
+
195
+ # Select scenario based on progressive difficulty
196
+ self.current_scenario = self.scenario_engine.get_scenarios_for_phase(self._total_episodes)
197
+
198
+ # Reset state
199
+ self._state = State(
200
+ episode_id=episode_id or str(uuid4()),
201
+ step_count=0,
202
+ )
203
+ self.action_history = []
204
+ self.episode_log = []
205
+ self.last_reward_info = {"total": 0.0}
206
+
207
+ # Initialize relationships for this episode
208
+ self.relationships = {}
209
+ for char_id in self.current_scenario.characters_involved:
210
+ char = get_character(char_id)
211
+ if char:
212
+ self.relationships[char_id] = char.initial_relationship
213
+
214
+ return Observation(
215
+ done=False,
216
+ reward=0.0,
217
+ metadata={
218
+ "message": f"New Scenario Loaded: {self.current_scenario.title}",
219
+ "hint": "Use call_tool('get_scenario_info') to start!"
220
+ },
221
+ )
222
+
223
+ def _step_impl(
224
+ self,
225
+ action: Action,
226
+ timeout_s: Optional[float] = None,
227
+ **kwargs: Any,
228
+ ) -> Observation:
229
+ """Handle non-MCP actions (we don't support any, so return error)."""
230
+ return Observation(
231
+ done=False,
232
+ reward=0.0,
233
+ metadata={"error": "Use ListToolsAction or CallToolAction for MCP interactions."},
234
+ )
235
+
236
+ def step(
237
+ self,
238
+ action: Action,
239
+ timeout_s: Optional[float] = None,
240
+ **kwargs: Any,
241
+ ) -> Observation:
242
+ """Execute a step via MCP tools."""
243
+ # Process the tool call
244
+ obs = super().step(action, timeout_s=timeout_s, **kwargs)
245
+
246
+ # Update step count if an action was actually chosen
247
+ if hasattr(action, 'tool_name') and action.tool_name == "choose_action":
248
+ self._state.step_count += 1
249
+
250
+ # Check done condition
251
+ done = False
252
+ if self.current_scenario and self._state.step_count >= self.current_scenario.max_steps:
253
+ done = True
254
+
255
+ # Inject custom reward info while preserving the original observation type.
256
+ if hasattr(obs, "done"):
257
+ obs.done = done
258
+ if hasattr(obs, "reward"):
259
+ obs.reward = self.last_reward_info.get("total", 0.0)
260
+ if hasattr(obs, "metadata"):
261
+ obs.metadata = self.last_reward_info
262
+ return obs
263
+
264
+ return obs
265
+
266
+ async def step_async(self, action: Action, timeout_s: Optional[float] = None, **kwargs: Any) -> Observation:
267
+ obs = await super().step_async(action, timeout_s=timeout_s, **kwargs)
268
+ if hasattr(action, 'tool_name') and action.tool_name == "choose_action":
269
+ self._state.step_count += 1
270
+ done = bool(self.current_scenario and self._state.step_count >= self.current_scenario.max_steps)
271
+ if hasattr(obs, "done"):
272
+ obs.done = done
273
+ if hasattr(obs, "reward"):
274
+ obs.reward = self.last_reward_info.get("total", 0.0)
275
+ if hasattr(obs, "metadata"):
276
+ obs.metadata = self.last_reward_info
277
+ return obs
278
+ return obs
279
+
280
+ @property
281
+ def state(self) -> State:
282
+ return self._state
server/static/blog.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shin-chan life simulator — mini blog
2
+
3
+ **Hosted on the Hugging Face Space (same host as the OpenEnv server).**
4
+ This file is the hackathon “mini write-up” you can link from the project README:
5
+ `https://<your-space>.hf.space/blog.md`
6
+
7
+ ## What is this environment?
8
+
9
+ A social/family *choose-your-outcome* loop: Shin-chan faces dilemmas, picks an action, and gets a **dense reward** (relationships, responsibility, in-character behavior). The goal of RL here is to learn a policy that keeps Shin-chan’s personality while **reducing bad outcomes** on average.
10
+
11
+ ## Why OpenEnv + TRL GRPO?
12
+
13
+ - **OpenEnv** exposes the world as **HTTP/MCP tools** so you can train against a *live* environment (local or on a Space).
14
+ - **TRL GRPO** fits **tool-calling** LLMs: the policy proposes `choose_action` calls; rewards come from the same engine judges use in evaluation.
15
+
16
+ ## What I actually trained
17
+
18
+ - **Model:** `Qwen/Qwen3-0.6B` (small, reliable on Colab; optional **QLoRA** for memory).
19
+ - **Signal:** per-step `reward` / `reward_components` returned by the environment.
20
+ - **Evidence:** `training/artifacts/**` in the git repo: `run_metadata.json`, `metrics.jsonl`, `trainer_state.json`, plus `assets/reward_curve_total.png` and `assets/loss_curve.png` from `plot_metrics.py`.
21
+
22
+ ## How to verify the Space
23
+
24
+ 1. Open `/gradio` for a simple human UI (state, action, reward).
25
+ 2. Open `/web` for the OpenEnv playground.
26
+ 3. `GET /health` should return `{"status": "ok"}`.
27
+
28
+ ## Honest note
29
+
30
+ This post is a **short narrative + pointers to artifacts**; the README and the Colab notebook document exact commands, seeds, and where plots are produced.
31
+
32
+ ---
33
+
34
+ *Update this file on the Hub with your run IDs and Space URL when you publish.*
server/static/sinchan/index.html ADDED
@@ -0,0 +1,1176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en" data-theme="day">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Shin-chan Life — Oops! Simulator</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
9
+ <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@500;600;700&family=Lilita+One&family=Nunito:wght@500;600;700&display=swap" rel="stylesheet" />
10
+ <style>
11
+ :root, [data-theme="day"] {
12
+ --k-teal: #2a9d8f;
13
+ --k-teal-dark: #1d7a6f;
14
+ --k-cream: #f7e7a1;
15
+ --k-cream-2: #fff9e6;
16
+ --k-sand: #e8d4a8;
17
+ --k-pink: #f28ebf;
18
+ --k-pink-deep: #d85fa3;
19
+ --k-sky: #5fb8e1;
20
+ --k-sky-bright: #7ec8e8;
21
+ --k-grass: #5cad46;
22
+ --k-grass-deep: #3d8c30;
23
+ --k-ink: #1b2838;
24
+ --k-white: #fffef9;
25
+ --k-red: #e63946;
26
+ --k-yellow: #ffe066;
27
+ --k-orange: #ff8c42;
28
+ --k-shadow: rgba(20, 40, 50, 0.15);
29
+ }
30
+
31
+ [data-theme="night"] {
32
+ --k-teal: #1e3a5f;
33
+ --k-teal-dark: #0d1b2a;
34
+ --k-cream: #8ecae6;
35
+ --k-cream-2: #4a6fa5;
36
+ --k-sand: #1b263b;
37
+ --k-pink: #d4a5c7;
38
+ --k-pink-deep: #b87fa8;
39
+ --k-sky: #4cc9f0;
40
+ --k-sky-bright: #6dd5fa;
41
+ --k-grass: #2b5f44;
42
+ --k-grass-deep: #1a3d2a;
43
+ --k-ink: #e8f1f5;
44
+ --k-white: #0f172a;
45
+ --k-red: #ff6b6b;
46
+ --k-yellow: #ffd166;
47
+ --k-orange: #ff8c64;
48
+ --k-shadow: rgba(0, 0, 0, 0.45);
49
+ }
50
+
51
+ * { box-sizing: border-box; }
52
+ button { font: inherit; }
53
+
54
+ body {
55
+ margin: 0;
56
+ min-height: 100vh;
57
+ font-family: "Nunito", system-ui, sans-serif;
58
+ color: var(--k-ink);
59
+ background: var(--k-ink);
60
+ overflow-x: hidden;
61
+ }
62
+
63
+ .bg-layers {
64
+ position: fixed;
65
+ inset: 0;
66
+ z-index: 0;
67
+ background: linear-gradient(180deg, var(--k-sky-bright) 0%, var(--k-sky) 38%, var(--k-cream) 38%, var(--k-sand) 100%);
68
+ transition: background 0.5s ease;
69
+ }
70
+ [data-theme="night"] .bg-layers {
71
+ background: linear-gradient(180deg, #0d1b2a 0%, #1b263b 40%, #243352 100%);
72
+ }
73
+ .bg-layers::before {
74
+ content: "";
75
+ position: absolute;
76
+ inset: 0;
77
+ background:
78
+ radial-gradient(ellipse 120% 80% at 20% 25%, rgba(255,255,255,.5) 0%, transparent 50%),
79
+ radial-gradient(ellipse 100% 60% at 80% 15%, rgba(255,255,255,.25) 0%, transparent 45%);
80
+ pointer-events: none;
81
+ }
82
+ [data-theme="night"] .bg-layers::before {
83
+ background: radial-gradient(2px 2px at 10% 8%, #fff8 0%, transparent 100%),
84
+ radial-gradient(1.5px 1.5px at 25% 15%, #fff6 0%, transparent 100%),
85
+ radial-gradient(1px 1px at 50% 10%, #fff4 0%, transparent 100%),
86
+ radial-gradient(1.5px 1.5px at 75% 20%, #fff5 0%, transparent 100%),
87
+ radial-gradient(1px 1px at 90% 12%, #fff3 0%, transparent 100%);
88
+ background-size: 200% 200%;
89
+ opacity: 0.85;
90
+ }
91
+
92
+ .toy-grass {
93
+ position: fixed;
94
+ bottom: 0;
95
+ left: 0;
96
+ right: 0;
97
+ height: min(18vh, 120px);
98
+ z-index: 0;
99
+ background: linear-gradient(0deg, var(--k-grass) 0%, var(--k-grass-deep) 100%);
100
+ clip-path: polygon(0 45%, 4% 35%, 8% 48%, 14% 30%, 20% 42%, 28% 25%, 36% 40%, 44% 28%, 52% 38%, 60% 22%, 68% 36%, 76% 26%, 84% 40%, 92% 32%, 100% 45%, 100% 100%, 0 100%);
101
+ opacity: 0.9;
102
+ transform-origin: 50% 100%;
103
+ animation: grass-breathe 10s ease-in-out infinite;
104
+ }
105
+ [data-theme="night"] .toy-grass {
106
+ opacity: 0.5;
107
+ }
108
+ @keyframes grass-breathe {
109
+ 0%, 100% { transform: scaleX(1) translateY(0); }
110
+ 50% { transform: scaleX(1.01) translateY(-1px); }
111
+ }
112
+
113
+ .site-top {
114
+ position: sticky;
115
+ top: 0;
116
+ z-index: 20;
117
+ display: flex;
118
+ align-items: center;
119
+ justify-content: space-between;
120
+ gap: 0.75rem;
121
+ padding: 0.65rem 1rem;
122
+ background: linear-gradient(180deg, var(--k-teal) 0%, var(--k-teal-dark) 100%);
123
+ color: #fff;
124
+ box-shadow: 0 4px 20px var(--k-shadow);
125
+ border-bottom: 3px solid rgba(0,0,0,.15);
126
+ animation: bar-drop 0.55s cubic-bezier(0.22, 1, 0.36, 1) backwards;
127
+ }
128
+ @keyframes bar-drop {
129
+ from { transform: translateY(-100%); opacity: 0.6; }
130
+ }
131
+ .brand {
132
+ display: flex;
133
+ align-items: center;
134
+ gap: 0.5rem;
135
+ font-family: "Fredoka", sans-serif;
136
+ font-weight: 700;
137
+ font-size: 1.05rem;
138
+ letter-spacing: 0.03em;
139
+ }
140
+ .brand-badge {
141
+ width: 32px; height: 32px;
142
+ background: var(--k-yellow);
143
+ border: 2px solid #1112;
144
+ border-radius: 10px;
145
+ display: grid;
146
+ place-items: center;
147
+ font-size: 0.7rem;
148
+ color: #c41e3a;
149
+ }
150
+ .top-actions { display: flex; align-items: center; gap: 0.5rem; }
151
+ .theme-btn {
152
+ display: flex;
153
+ align-items: center;
154
+ gap: 0.4rem;
155
+ padding: 0.35rem 0.7rem;
156
+ background: rgba(255,255,255,.2);
157
+ border: 2px solid rgba(255,255,255,.35);
158
+ border-radius: 999px;
159
+ color: #fff;
160
+ cursor: pointer;
161
+ font-size: 0.8rem;
162
+ font-weight: 600;
163
+ }
164
+ .theme-btn { transition: transform 0.2s ease, background 0.2s; }
165
+ .theme-btn:hover { background: rgba(255,255,255,.3); transform: scale(1.04); }
166
+ .theme-btn:active { transform: scale(0.98); }
167
+ .pill-live {
168
+ font-size: 0.65rem;
169
+ text-transform: uppercase;
170
+ letter-spacing: 0.1em;
171
+ background: var(--k-pink);
172
+ color: #1a1a1a;
173
+ padding: 0.15rem 0.4rem;
174
+ border-radius: 4px;
175
+ font-weight: 800;
176
+ }
177
+
178
+ .page {
179
+ position: relative;
180
+ z-index: 1;
181
+ max-width: 960px;
182
+ margin: 0 auto;
183
+ padding: 0 1rem 3rem;
184
+ animation: page-rise 0.7s cubic-bezier(0.22, 1, 0.36, 1) backwards 0.1s;
185
+ }
186
+ @keyframes page-rise { from { opacity: 0; transform: translateY(16px); } }
187
+ .hero { animation: page-rise 0.6s ease backwards; }
188
+
189
+ .hero {
190
+ text-align: center;
191
+ padding: 1.75rem 0 0.5rem;
192
+ }
193
+ .hero-ribbon {
194
+ display: inline-block;
195
+ font-family: "Fredoka", sans-serif;
196
+ font-size: 0.7rem;
197
+ text-transform: uppercase;
198
+ letter-spacing: 0.2em;
199
+ color: #fff;
200
+ background: var(--k-pink);
201
+ border: 2px solid var(--k-pink-deep);
202
+ padding: 0.25rem 0.8rem;
203
+ border-radius: 999px;
204
+ margin-bottom: 0.5rem;
205
+ box-shadow: 0 2px 0 var(--k-pink-deep);
206
+ animation: ribbon-in 0.6s cubic-bezier(0.34, 1.3, 0.64, 1) backwards, ribbon-pulse 3s ease-in-out infinite 0.6s;
207
+ }
208
+ @keyframes ribbon-in { from { transform: scale(0) rotate(-6deg); opacity: 0; } }
209
+ @keyframes ribbon-pulse { 0%, 100% { box-shadow: 0 2px 0 var(--k-pink-deep), 0 0 0 0 #f9a8d466; } 50% { box-shadow: 0 2px 0 var(--k-pink-deep), 0 0 0 8px transparent; } }
210
+ h1 {
211
+ font-family: "Fredoka", sans-serif;
212
+ font-weight: 700;
213
+ font-size: clamp(1.6rem, 4.2vw, 2.4rem);
214
+ line-height: 1.1;
215
+ margin: 0;
216
+ text-shadow: 0 2px 0 #fff, 0 4px 0 rgba(0,0,0,.08);
217
+ color: var(--k-ink);
218
+ background: linear-gradient(100deg, var(--k-ink) 0%, #e63946 40%, #f59e0b 60%, var(--k-ink) 100%);
219
+ background-size: 200% auto;
220
+ -webkit-background-clip: text;
221
+ background-clip: text;
222
+ -webkit-text-fill-color: transparent;
223
+ animation: title-sheen 5s ease infinite;
224
+ }
225
+ [data-theme="night"] h1 {
226
+ background: linear-gradient(100deg, #e8f4f8 0%, #7dd3fc 35%, #fda4af 60%, #e8f4f8 100%);
227
+ background-size: 200% auto;
228
+ -webkit-background-clip: text;
229
+ background-clip: text;
230
+ -webkit-text-fill-color: transparent;
231
+ }
232
+ @keyframes title-sheen {
233
+ 0%, 100% { background-position: 0% 50%; }
234
+ 50% { background-position: 100% 50%; }
235
+ }
236
+ .tagline {
237
+ font-size: 0.95rem;
238
+ color: #3d5360;
239
+ max-width: 32rem;
240
+ margin: 0.5rem auto 0;
241
+ line-height: 1.45;
242
+ }
243
+ [data-theme="night"] .tagline { color: #9cb4c4; }
244
+
245
+ .hero-float {
246
+ display: flex;
247
+ justify-content: center;
248
+ align-items: flex-end;
249
+ gap: 1.25rem;
250
+ min-height: 200px;
251
+ margin: 0.5rem 0 1.25rem;
252
+ }
253
+
254
+ .hero-mascot {
255
+ position: relative;
256
+ display: flex;
257
+ align-items: flex-end;
258
+ justify-content: center;
259
+ gap: 1.25rem;
260
+ }
261
+ .mascot-sparkle { position: absolute; inset: 0; pointer-events: none; }
262
+ .mascot-sparkle i {
263
+ position: absolute;
264
+ width: 6px; height: 6px;
265
+ background: #fff;
266
+ border-radius: 2px;
267
+ rotate: 45deg;
268
+ opacity: 0;
269
+ animation: sparkle-pop 2.2s ease-in-out infinite;
270
+ }
271
+ .mascot-sparkle i:nth-child(1) { left: 8%; top: 30%; animation-delay: 0s; }
272
+ .mascot-sparkle i:nth-child(2) { right: 12%; top: 18%; animation-delay: 0.4s; width: 4px; height: 4px; }
273
+ .mascot-sparkle i:nth-child(3) { left: 20%; top: 8%; animation-delay: 0.8s; }
274
+ .mascot-sparkle i:nth-child(4) { right: 8%; top: 38%; animation-delay: 1.1s; }
275
+ @keyframes sparkle-pop { 0%, 100% { opacity: 0; transform: scale(0) rotate(45deg); } 20% { opacity: 0.9; } 50% { opacity: 0.5; } }
276
+
277
+ .clouds {
278
+ position: absolute;
279
+ left: 5%;
280
+ right: 5%;
281
+ top: 120px;
282
+ height: 60px;
283
+ pointer-events: none;
284
+ z-index: 0;
285
+ }
286
+ [data-theme="night"] .clouds { display: none; }
287
+ .clouds span {
288
+ position: absolute;
289
+ background: #fff8;
290
+ border-radius: 50px;
291
+ filter: blur(0.5px);
292
+ animation: floaty 6s ease-in-out infinite;
293
+ }
294
+ .clouds span:nth-child(1) { width: 64px; height: 24px; left: 0; top: 20px; animation-delay: 0s; }
295
+ .clouds span:nth-child(2) { width: 88px; height: 30px; left: 15%; top: 0; animation-delay: 0.5s; }
296
+ .clouds span:nth-child(3) { width: 70px; height: 22px; right: 10%; top: 28px; animation-delay: 1s; }
297
+ @keyframes floaty {
298
+ 0%, 100% { transform: translateY(0); }
299
+ 50% { transform: translateY(-6px); }
300
+ }
301
+
302
+ .mascot {
303
+ position: relative;
304
+ width: 150px;
305
+ height: 180px;
306
+ filter: drop-shadow(4px 8px 12px rgba(0,0,0,.2));
307
+ animation: mascot-bob 2.4s ease-in-out infinite;
308
+ transform-origin: 50% 90%;
309
+ }
310
+ @keyframes mascot-bob {
311
+ 0%, 100% { transform: translateY(0) rotate(0deg); }
312
+ 50% { transform: translateY(-8px) rotate(-1.5deg); }
313
+ }
314
+ .mascot.oops { animation: mascot-panic 0.45s ease-in-out 4, mascot-bob 2.4s ease-in-out infinite; }
315
+ @keyframes mascot-panic {
316
+ 0%, 100% { transform: translate(0) rotate(0); }
317
+ 20% { transform: translate(-4px, 2px) rotate(-6deg) scale(1.02); }
318
+ 40% { transform: translate(5px, -2px) rotate(7deg) scale(1.02); }
319
+ 60% { transform: translate(-3px) rotate(-4deg); }
320
+ 80% { transform: translate(3px) rotate(3deg); }
321
+ }
322
+ .mascot-svg {
323
+ width: 100%;
324
+ height: 100%;
325
+ display: block;
326
+ overflow: visible;
327
+ }
328
+ .mascot-svg .mascot-rig { transform-origin: 50% 100%; }
329
+ .mascot-sway { animation: rig-sway 3s ease-in-out infinite; transform-origin: 50px 100px; }
330
+ @keyframes rig-sway { 0%, 100% { transform: rotate(0); } 50% { transform: rotate(1.2deg); } }
331
+ .mascot-arm-l {
332
+ transform-origin: 16px 72px;
333
+ transform-box: fill-box;
334
+ animation: arm-l 1.8s ease-in-out infinite;
335
+ }
336
+ .mascot-arm-r {
337
+ transform-origin: 84px 72px;
338
+ transform-box: fill-box;
339
+ animation: arm-r 1.8s ease-in-out infinite;
340
+ }
341
+ @keyframes arm-l { 0%, 100% { transform: rotate(-6deg); } 50% { transform: rotate(4deg); } }
342
+ @keyframes arm-r { 0%, 100% { transform: rotate(6deg); } 50% { transform: rotate(-4deg); } }
343
+ .mascot-pupils { animation: look-dart 5s ease-in-out infinite; transform-box: fill-box; transform-origin: 50px 40px; }
344
+ @keyframes look-dart {
345
+ 0%, 22% { transform: translate(0, 0); }
346
+ 28%, 42% { transform: translate(0.8px, 0.4px); }
347
+ 50%, 100% { transform: translate(0, 0); }
348
+ }
349
+ .mascot-mouth-h, .mascot-mouth-o { transition: opacity 0.1s ease; }
350
+ .mascot-mouth-o { opacity: 0; }
351
+ .mascot-sweat { transition: opacity 0.2s; opacity: 0; }
352
+ .mascot.oops .mascot-mouth-h { opacity: 0; }
353
+ .mascot.oops .mascot-mouth-o { opacity: 1; }
354
+ .mascot.oops .mascot-sweat { opacity: 1; }
355
+ @keyframes sweat-drip { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(2.5px); } }
356
+ .mascot.oops .mascot-sweat path { animation: sweat-drip 0.55s ease-in-out infinite; }
357
+
358
+ .mascot-wrap { position: relative; display: inline-block; }
359
+ @media (max-width: 520px) {
360
+ .hero-mascot { flex-wrap: wrap; flex-direction: column; align-items: center; }
361
+ }
362
+
363
+ .oops-sticker {
364
+ position: relative;
365
+ z-index: 2;
366
+ padding: 0;
367
+ background: none;
368
+ border: none;
369
+ box-shadow: none;
370
+ transform: rotate(-4deg);
371
+ animation: oops-breathe 3.2s ease-in-out infinite;
372
+ }
373
+ .oops-sticker__text {
374
+ font-family: "Lilita One", cursive, sans-serif;
375
+ font-size: clamp(1.8rem, 4.2vw, 2.5rem);
376
+ line-height: 1;
377
+ color: #f2368c;
378
+ letter-spacing: 0.08em;
379
+ text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
380
+ }
381
+ [data-theme="night"] .oops-sticker__text {
382
+ color: #fda4c8;
383
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.35);
384
+ }
385
+ @keyframes oops-breathe {
386
+ 0%, 100% { transform: rotate(-4deg) scale(1); }
387
+ 50% { transform: rotate(-2deg) scale(1.02); }
388
+ }
389
+ .oops-sticker.oops-bump {
390
+ animation: oops-bump 0.55s cubic-bezier(0.34, 1.4, 0.64, 1) both;
391
+ }
392
+ @keyframes oops-bump {
393
+ 0% { transform: rotate(-6deg) scale(1.2); }
394
+ 100% { transform: rotate(-4deg) scale(1); }
395
+ }
396
+
397
+ .layout {
398
+ display: grid;
399
+ gap: 1rem;
400
+ }
401
+ @media (min-width: 900px) {
402
+ .layout.has-play {
403
+ grid-template-columns: 1fr 1.05fr;
404
+ align-items: start;
405
+ }
406
+ }
407
+
408
+ .card {
409
+ background: linear-gradient(145deg, var(--k-cream-2) 0%, #fff 40%, #fff8 100%);
410
+ border-radius: 20px;
411
+ border: 3px solid #0002;
412
+ box-shadow: 0 4px 0 #0001, 8px 10px 24px var(--k-shadow);
413
+ padding: 1.1rem 1.25rem;
414
+ margin-bottom: 0.25rem;
415
+ position: relative;
416
+ overflow: hidden;
417
+ }
418
+ [data-theme="night"] .card {
419
+ background: linear-gradient(160deg, #1b263b 0%, #172035 100%);
420
+ border-color: #3a4a63;
421
+ }
422
+ .card::before {
423
+ content: "";
424
+ position: absolute;
425
+ left: 0; top: 0; bottom: 0;
426
+ width: 5px;
427
+ background: linear-gradient(180deg, var(--k-pink) 0%, var(--k-sky) 100%);
428
+ }
429
+ .card h2, .card .h2 {
430
+ font-family: "Fredoka", sans-serif;
431
+ font-size: 1.1rem;
432
+ margin: 0 0 0.65rem 0.35rem;
433
+ color: var(--k-teal-dark);
434
+ }
435
+ [data-theme="night"] .card h2, [data-theme="night"] .card .h2 { color: var(--k-sky); }
436
+ .card .eyebrow {
437
+ font-size: 0.7rem;
438
+ text-transform: uppercase;
439
+ letter-spacing: 0.12em;
440
+ color: #64748b;
441
+ margin: 0 0 0.15rem 0.35rem;
442
+ }
443
+ [data-theme="night"] .card .eyebrow { color: #94a3b8; }
444
+ .card.in-view { animation: cardIn 0.55s cubic-bezier(0.22, 1.1, 0.36, 1) backwards; }
445
+ @keyframes cardIn { from { opacity: 0; transform: translateY(14px) scale(0.99);} }
446
+
447
+ .narrative {
448
+ line-height: 1.7;
449
+ font-size: 0.95rem;
450
+ color: #334;
451
+ margin-left: 0.35rem;
452
+ }
453
+ [data-theme="night"] .narrative { color: #cbd5e1; }
454
+
455
+ .pill {
456
+ display: inline-block;
457
+ background: var(--k-sky);
458
+ color: #fff;
459
+ padding: 0.25rem 0.7rem;
460
+ border-radius: 999px;
461
+ font-size: 0.75rem;
462
+ font-weight: 600;
463
+ margin: 0.2rem 0.2rem 0 0;
464
+ border: 2px solid #0288b5;
465
+ }
466
+ [data-theme="night"] .pill {
467
+ background: #2563eb;
468
+ border-color: #1d4ed8;
469
+ }
470
+
471
+ .actions { display: flex; flex-direction: column; gap: 0.55rem; }
472
+ .act-btn {
473
+ text-align: left;
474
+ cursor: pointer;
475
+ padding: 0.8rem 1rem;
476
+ border-radius: 14px;
477
+ border: 2px solid #0001;
478
+ background: #fff;
479
+ box-shadow: 0 2px 0 #0001, 4px 4px 0 var(--k-grass);
480
+ transition: box-shadow 0.12s, transform 0.12s, border-color 0.2s, background 0.2s;
481
+ }
482
+ [data-theme="night"] .act-btn {
483
+ background: #0f172a;
484
+ box-shadow: 0 2px 0 #0004, 4px 4px 0 #1e3a2f;
485
+ }
486
+ .act-btn:hover:not(:disabled) { transform: translate(2px, 2px); box-shadow: 0 0 0 #0000, 2px 2px 0 var(--k-grass); }
487
+ [data-theme="night"] .act-btn:hover:not(:disabled) { box-shadow: 0 0 0, 2px 2px 0 #0d2818; }
488
+ .act-btn[aria-pressed="true"] {
489
+ border-color: var(--k-pink);
490
+ background: #fff0f6;
491
+ box-shadow: 0 0 0 3px #f9a8d4, 4px 4px 0 var(--k-pink-deep);
492
+ }
493
+ [data-theme="night"] .act-btn[aria-pressed="true"] {
494
+ background: #2a1a30;
495
+ box-shadow: 0 0 0 2px #d946a6;
496
+ }
497
+ .act-btn:disabled { opacity: 0.5; cursor: not-allowed; }
498
+ .stagger-children .act-btn {
499
+ animation: act-in 0.42s cubic-bezier(0.22, 1, 0.35, 1) backwards;
500
+ animation-delay: calc(var(--st, 0) * 50ms);
501
+ }
502
+ @keyframes act-in { from { opacity: 0; transform: translateX(-14px) scale(0.98); } }
503
+ .act-name { font-family: "Fredoka", sans-serif; font-weight: 600; color: #c41e3a; font-size: 0.92rem; }
504
+ [data-theme="night"] .act-name { color: #fca5a5; }
505
+ .act-desc { font-size: 0.82rem; color: #475569; margin-top: 0.2rem; }
506
+ [data-theme="night"] .act-desc { color: #94a3b8; }
507
+
508
+ label { display: block; font-size: 0.78rem; font-weight: 700; margin: 0.6rem 0.35rem 0.25rem; text-transform: uppercase; letter-spacing: 0.06em; }
509
+ [data-theme="night"] label { color: #94a3b8; }
510
+ .field {
511
+ margin-left: 0.35rem;
512
+ }
513
+ textarea, input[type="text"] {
514
+ width: 100%;
515
+ border: 2px solid #0002;
516
+ border-radius: 12px;
517
+ padding: 0.55rem 0.7rem;
518
+ font-family: inherit;
519
+ font-size: 0.9rem;
520
+ background: #fff;
521
+ }
522
+ [data-theme="night"] textarea, [data-theme="night"] input[type="text"] {
523
+ background: #0f172a;
524
+ color: #e2e8f0;
525
+ border-color: #334155;
526
+ }
527
+ textarea { min-height: 3.4rem; resize: vertical; }
528
+
529
+ .row-btns { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0.9rem 0.35rem 0; }
530
+ .primary {
531
+ display: inline-flex;
532
+ align-items: center;
533
+ justify-content: center;
534
+ gap: 0.4rem;
535
+ font-family: "Fredoka", sans-serif;
536
+ font-weight: 600;
537
+ cursor: pointer;
538
+ padding: 0.7rem 1.35rem;
539
+ border: none;
540
+ border-radius: 999px;
541
+ background: linear-gradient(180deg, var(--k-red) 0%, #c41e3a 100%);
542
+ color: #fff;
543
+ box-shadow: 0 4px 0 #7f1d1d, 0 6px 16px #e6394644;
544
+ transition: filter 0.2s, transform 0.15s;
545
+ }
546
+ .primary:hover:not(:disabled) { filter: brightness(1.08) saturate(1.05); }
547
+ .primary:active:not(:disabled) { transform: translateY(2px); box-shadow: 0 2px 0 #7f1d1d; }
548
+ .primary:disabled { opacity: 0.45; cursor: not-allowed; }
549
+ .secondary {
550
+ font-family: "Fredoka", sans-serif;
551
+ cursor: pointer;
552
+ padding: 0.65rem 1rem;
553
+ border-radius: 999px;
554
+ border: 2px solid #0002;
555
+ background: var(--k-cream);
556
+ color: #333;
557
+ }
558
+ [data-theme="night"] .secondary { background: #334155; color: #e2e8f0; border-color: #475569; }
559
+
560
+ .status { font-size: 0.8rem; color: #64748b; margin: 0.5rem 0.35rem 0; }
561
+ [data-theme="night"] .status { color: #94a3b8; }
562
+ .err { color: #b91c1c; font-weight: 600; }
563
+ [data-theme="night"] .err { color: #fecaca; }
564
+
565
+ .result-lane { display: flex; flex-direction: column; gap: 0.6rem; }
566
+
567
+ .speech {
568
+ position: relative;
569
+ background: #e0f2fe;
570
+ border: 2px solid #0284c7;
571
+ border-radius: 16px;
572
+ padding: 0.8rem 1rem;
573
+ font-size: 0.9rem;
574
+ }
575
+ [data-theme="night"] .speech { background: #132337; border-color: #0ea5e9; color: #e0f2fe; }
576
+ .speech.win { background: #ecfdf5; border-color: #10b981; }
577
+ [data-theme="night"] .speech.win { background: #123329; border-color: #22c55e; }
578
+
579
+ .meter {
580
+ display: flex; align-items: center; gap: 0.75rem;
581
+ padding: 0.4rem 0.2rem;
582
+ }
583
+ .meter .bar {
584
+ flex: 1; height: 14px; background: #e2e8f0; border-radius: 7px; overflow: hidden; border: 2px solid #94a3b8;
585
+ }
586
+ [data-theme="night"] .meter .bar { background: #1e293b; border-color: #475569; }
587
+ .meter .fill {
588
+ height: 100%;
589
+ background: linear-gradient(90deg, #ef4444, var(--k-yellow) 50%, #22c55e);
590
+ border-radius: 5px;
591
+ transition: width 0.55s cubic-bezier(0.2, 0.9, 0.2, 1);
592
+ }
593
+ .meter .score-num {
594
+ font-family: "Fredoka", sans-serif;
595
+ font-size: 1.1rem;
596
+ font-weight: 700;
597
+ min-width: 3rem;
598
+ text-align: right;
599
+ }
600
+
601
+ .melt-banner {
602
+ background: linear-gradient(100deg, #fb7185, var(--k-orange) 50%, #f59e0b);
603
+ color: #fff;
604
+ padding: 0.85rem 1rem;
605
+ border-radius: 14px;
606
+ font-family: "Fredoka", sans-serif;
607
+ font-weight: 700;
608
+ text-align: center;
609
+ text-shadow: 0 1px 2px #0003;
610
+ border: 2px solid #7f1d1d4d;
611
+ }
612
+
613
+ .score-grid {
614
+ display: grid;
615
+ grid-template-columns: repeat(auto-fill, minmax(128px, 1fr));
616
+ gap: 0.4rem;
617
+ font-size: 0.75rem;
618
+ }
619
+ .score-grid div {
620
+ background: #f1f5f9;
621
+ border-radius: 10px;
622
+ padding: 0.4rem 0.5rem;
623
+ border: 1px solid #cbd5e1;
624
+ }
625
+ [data-theme="night"] .score-grid div { background: #0f172a; border-color: #334155; }
626
+
627
+ .rel-row {
628
+ display: flex; align-items: center; gap: 0.5rem; margin: 0.4rem 0; font-size: 0.88rem;
629
+ }
630
+ .rel-avatar {
631
+ width: 28px; height: 28px; border-radius: 8px; background: var(--k-sky);
632
+ color: #fff; font-size: 0.65rem; font-weight: 800; display: grid; place-items: center; flex-shrink: 0;
633
+ }
634
+ .rel-bar-wrap { flex: 1; height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; }
635
+ [data-theme="night"] .rel-bar-wrap { background: #1e293b; }
636
+ .rel-bar { height: 100%; background: linear-gradient(90deg, var(--k-pink), #22c55e); border-radius: 4px; transition: width 0.4s ease; }
637
+
638
+ footer { text-align: center; font-size: 0.7rem; color: #64748b; margin: 2.5rem 0 0.5rem; }
639
+ [data-theme="night"] footer { color: #64748b; }
640
+
641
+ .confetti { pointer-events: none; position: fixed; inset: 0; z-index: 30; overflow: hidden; }
642
+ .confetti i {
643
+ position: absolute;
644
+ top: -10px; width: 8px; height: 12px; border-radius: 2px;
645
+ animation: confetti-fall 2.5s ease-out forwards;
646
+ }
647
+ @keyframes confetti-fall {
648
+ to { transform: translateY(100vh) rotate(720deg); opacity: 0.9; }
649
+ }
650
+ .shake { animation: shake 0.4s ease; }
651
+ @keyframes shake {
652
+ 0%, 100% { transform: translateX(0); }
653
+ 20% { transform: translateX(-6px); }
654
+ 40% { transform: translateX(6px); }
655
+ 60% { transform: translateX(-4px); }
656
+ 80% { transform: translateX(4px); }
657
+ }
658
+
659
+ @media (prefers-reduced-motion: reduce) {
660
+ .page, .hero, .mascot, .mascot-arm-l, .mascot-arm-r, .mascot-sway, .mascot-pupils,
661
+ .mascot-sweat path, .mascot.oops, .toy-grass, .confetti i, h1, .hero-ribbon, .mascot-sparkle i,
662
+ .card.in-view, .stagger-children .act-btn, .site-top, .mascot-sparkle i,
663
+ .oops-sticker {
664
+ animation: none !important;
665
+ transition: none !important;
666
+ }
667
+ .mascot, .mascot-pupils { transform: none !important; }
668
+ .oops-sticker { transform: rotate(-4deg) !important; }
669
+ }
670
+ </style>
671
+ </head>
672
+ <body>
673
+ <div class="bg-layers" aria-hidden="true"></div>
674
+ <div class="toy-grass" aria-hidden="true"></div>
675
+ <div class="clouds" aria-hidden="true"><span></span><span></span><span></span></div>
676
+ <div class="confetti" id="confetti" aria-hidden="true"></div>
677
+
678
+ <header class="site-top">
679
+ <div class="brand">
680
+ <span class="brand-badge" aria-hidden="true">野</span>
681
+ <span>Shin-chan Life</span>
682
+ <span class="pill-live">Oops! Lab</span>
683
+ </div>
684
+ <div class="top-actions">
685
+ <button type="button" class="theme-btn" id="btnTheme" title="Toggle day / night look">
686
+ <span id="themeIcon">&#127774;</span>
687
+ <span id="themeLabel">Day at school</span>
688
+ </button>
689
+ </div>
690
+ </header>
691
+
692
+ <div class="page">
693
+ <section class="hero">
694
+ <div class="hero-ribbon">Crayon-coloured · OpenEnv</div>
695
+ <h1>Life simulator —<br/>mistakes included</h1>
696
+ <p class="tagline">Pick wild choices, watch the fallout, and see if you still score points. It’s the kindergarten sandbox… with Nohara-level chaos energy.</p>
697
+ </section>
698
+
699
+ <div class="hero-float" aria-hidden="true">
700
+ <div class="hero-mascot">
701
+ <div class="mascot-sparkle"><i></i><i></i><i></i><i></i></div>
702
+ <div class="mascot-wrap">
703
+ <div class="mascot" id="chibi">
704
+ <svg class="mascot-svg" viewBox="0 0 100 120" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Stylized cartoon child mascot (original fan art)">
705
+ <defs>
706
+ <linearGradient id="mSkin" x1="0" y1="0" x2="0" y2="1">
707
+ <stop offset="0%" stop-color="#ffefd8"/>
708
+ <stop offset="55%" stop-color="#f5cba4"/>
709
+ <stop offset="100%" stop-color="#e8a87c"/>
710
+ </linearGradient>
711
+ <radialGradient id="mBlush" cx="50%" cy="50%" r="50%">
712
+ <stop offset="0%" stop-color="#ff8a80" stop-opacity="0.5"/>
713
+ <stop offset="100%" stop-color="#ff8a80" stop-opacity="0"/>
714
+ </radialGradient>
715
+ <linearGradient id="mShirt" x1="0" y1="0" x2="0" y2="1">
716
+ <stop offset="0%" stop-color="#f24848"/>
717
+ <stop offset="100%" stop-color="#b71c1c"/>
718
+ </linearGradient>
719
+ <linearGradient id="mShorts" x1="0" y1="0" x2="0" y2="1">
720
+ <stop offset="0%" stop-color="#fff176"/>
721
+ <stop offset="100%" stop-color="#ffb300"/>
722
+ </linearGradient>
723
+ <linearGradient id="mHair" x1="0" y1="0" x2="0" y2="1">
724
+ <stop offset="0%" stop-color="#1e1e1e"/>
725
+ <stop offset="100%" stop-color="#0a0a0a"/>
726
+ </linearGradient>
727
+ </defs>
728
+ <ellipse cx="50" cy="114" rx="30" ry="3.2" fill="rgba(0,0,0,0.12)"/>
729
+ <g class="mascot-rig mascot-sway">
730
+ <!-- Back → front: lower body, shirt, arms, then head -->
731
+ <path
732
+ d="M 32 90 L 30 100 L 70 100 L 68 90 Q 50 86 32 90 Z"
733
+ fill="url(#mShorts)"
734
+ stroke="#c49000"
735
+ stroke-width="0.5"
736
+ />
737
+ <line x1="50" y1="90" x2="50" y2="100" stroke="#a67c00" stroke-width="0.4" opacity="0.8"/>
738
+ <rect x="33" y="100" width="7" height="10" rx="1.2" fill="#ffe0a3" stroke="#d4a012" stroke-width="0.35"/>
739
+ <rect x="60" y="100" width="7" height="10" rx="1.2" fill="#ffe0a3" stroke="#d4a012" stroke-width="0.35"/>
740
+ <rect x="32" y="110" width="8" height="2.2" rx="0.3" fill="#3e2723"/>
741
+ <rect x="60" y="110" width="8" height="2.2" rx="0.3" fill="#3e2723"/>
742
+ <path
743
+ d="M 25 64 L 23 90 L 77 90 L 75 64 Q 50 56 25 64 Z"
744
+ fill="url(#mShirt)"
745
+ stroke="#5c0f0f"
746
+ stroke-width="0.75"
747
+ stroke-linejoin="round"
748
+ />
749
+ <g class="mascot-arm-l">
750
+ <path
751
+ d="M 25 64 Q 3 70 0 90 Q 7 100 20 95 Q 22 80 32 70 Q 32 64 32 64 Z"
752
+ fill="url(#mSkin)"
753
+ stroke="#c4956a"
754
+ stroke-width="0.4"
755
+ stroke-linejoin="round"
756
+ />
757
+ </g>
758
+ <g class="mascot-arm-r">
759
+ <path
760
+ d="M 75 64 Q 97 70 100 90 Q 93 100 80 95 Q 78 80 68 70 Q 68 64 68 64 Z"
761
+ fill="url(#mSkin)"
762
+ stroke="#c4956a"
763
+ stroke-width="0.4"
764
+ stroke-linejoin="round"
765
+ />
766
+ </g>
767
+ <rect x="44" y="59" width="12" height="5" fill="url(#mSkin)"/>
768
+ <ellipse cx="50" cy="42" rx="30" ry="27" fill="url(#mSkin)" stroke="#d4a05a" stroke-width="0.9"/>
769
+ <ellipse cx="17" cy="44" rx="3.4" ry="4" fill="url(#mSkin)" stroke="#c4956a" stroke-width="0.45"/>
770
+ <ellipse cx="83" cy="44" rx="3.4" ry="4" fill="url(#mSkin)" stroke="#c4956a" stroke-width="0.45"/>
771
+ <ellipse cx="50" cy="16" rx="32" ry="16" fill="url(#mHair)"/>
772
+ <path d="M 3 32 Q 0 50 2 70 L 10 64 Q 2 50 3 32 Z" fill="url(#mHair)"/>
773
+ <path d="M 97 32 Q 100 50 98 70 L 90 64 Q 100 50 97 32 Z" fill="url(#mHair)"/>
774
+ <ellipse cx="31" cy="47" rx="6" ry="3.2" fill="url(#mBlush)"/>
775
+ <ellipse cx="69" cy="47" rx="6" ry="3.2" fill="url(#mBlush)"/>
776
+ <path d="M 24 32 L 47 30 L 48 36 L 24 36 Z" fill="#0a0a0a"/>
777
+ <path d="M 76 32 L 53 30 L 52 36 L 76 36 Z" fill="#0a0a0a"/>
778
+ <g class="mascot-eyes-f">
779
+ <ellipse cx="39" cy="40" rx="4.4" ry="4.9" fill="#fff" stroke="#222" stroke-width="0.4"/>
780
+ <ellipse cx="61" cy="40" rx="4.4" ry="4.9" fill="#fff" stroke="#222" stroke-width="0.4"/>
781
+ <g class="mascot-pupils">
782
+ <circle cx="39" cy="40" r="2.1" fill="#141414"/>
783
+ <circle cx="61" cy="40" r="2.1" fill="#141414"/>
784
+ <circle cx="39.6" cy="38.9" r="0.65" fill="#fff"/>
785
+ <circle cx="61.6" cy="38.9" r="0.65" fill="#fff"/>
786
+ </g>
787
+ </g>
788
+ <path
789
+ class="mascot-mouth-h"
790
+ d="M 43 55 Q 50 60 57 55"
791
+ fill="none"
792
+ stroke="#3e2723"
793
+ stroke-width="1.1"
794
+ stroke-linecap="round"
795
+ />
796
+ <ellipse
797
+ class="mascot-mouth-o"
798
+ cx="50"
799
+ cy="55.5"
800
+ rx="4.4"
801
+ ry="5"
802
+ fill="#2d1b1b"
803
+ stroke="#5d4037"
804
+ stroke-width="0.35"
805
+ />
806
+ </g>
807
+ <g class="mascot-sweat" opacity="0" fill="none" stroke-width="0.2">
808
+ <path d="M 88 28 Q 92 8 90 0 Q 95 8 90 32 Z" fill="#81d4fa" stroke="#38bdf8" opacity="0.95"/>
809
+ <path d="M 10 26 Q 4 6 5 0 Q 0 6 4 32 Z" fill="#81d4fa" stroke="#38bdf8" opacity="0.9"/>
810
+ </g>
811
+ </svg>
812
+ </div>
813
+ </div>
814
+ <div class="oops-sticker" id="oopsSticker" aria-hidden="true">
815
+ <span class="oops-sticker__text">OOPS</span>
816
+ </div>
817
+ </div>
818
+ </div>
819
+
820
+ <div class="layout" id="mainLayout">
821
+ <div>
822
+ <div class="card in-view" id="setupCard" style="animation-delay:0s">
823
+ <div class="eyebrow">Session</div>
824
+ <h2 class="h2">Start a new episode</h2>
825
+ <p class="narrative">Spin up the env, load a life situation, and play as a five-year-old decision engine.</p>
826
+ <div class="row-btns">
827
+ <button type="button" class="primary" id="btnStart"><span>▶</span> Start / new episode</button>
828
+ </div>
829
+ <p class="status" id="setupStatus"></p>
830
+ </div>
831
+
832
+ <div class="card" id="sceneCard" style="display:none">
833
+ <div class="eyebrow" id="sceneEyebrow">Current moment</div>
834
+ <h2 class="h2" id="sceneTitle">—</h2>
835
+ <div class="narrative" id="sceneNarrative"></div>
836
+ <div id="charPills" style="margin:0.75rem 0 0"></div>
837
+ </div>
838
+ </div>
839
+
840
+ <div>
841
+ <div class="card" id="playCard" style="display:none">
842
+ <div class="eyebrow">Your turn</div>
843
+ <h2 class="h2">What should Shin-chan do?</h2>
844
+ <div class="actions" id="actionList"></div>
845
+ <div class="field">
846
+ <label for="dialogue">Line (out loud)</label>
847
+ <textarea id="dialogue" placeholder="Buri buri~! …">Buri buri! Here we go!</textarea>
848
+ </div>
849
+ <div class="field">
850
+ <label for="reasoning">Why (inner monologue)</label>
851
+ <input type="text" id="reasoning" placeholder="Chocobi vs Mom vs dignity…" />
852
+ </div>
853
+ <div class="row-btns">
854
+ <button type="button" class="primary" id="btnAct" disabled>Do it! ✦</button>
855
+ <button type="button" class="secondary" id="btnRescan">Refresh vibes</button>
856
+ </div>
857
+ <p class="status" id="actStatus"></p>
858
+ </div>
859
+
860
+ <div class="card" id="resultCard" style="display:none">
861
+ <div class="eyebrow">Aftermath</div>
862
+ <h2 class="h2">What happened</h2>
863
+ <div class="result-lane" id="resultBody"></div>
864
+ </div>
865
+ </div>
866
+ </div>
867
+
868
+ <div class="card" id="relCard" style="display:none; max-width: 100%;">
869
+ <div class="eyebrow">Crew</div>
870
+ <h2 class="h2">Relationship meters</h2>
871
+ <div id="relBody"></div>
872
+ </div>
873
+
874
+ <footer>Fan-made palette nod to the show’s colours — not affiliated. OpenEnv ShinChan project.</footer>
875
+ </div>
876
+
877
+ <script>
878
+ const THEME_KEY = "sinchan-ui-theme";
879
+ const API = (path) => (window.location.origin + path);
880
+ let rpcId = 0;
881
+ let sessionId = null;
882
+ let selectedAction = null;
883
+ let lastScenario = null;
884
+
885
+ function nextId() { rpcId += 1; return rpcId; }
886
+
887
+ function setTheme(t) {
888
+ document.documentElement.setAttribute("data-theme", t);
889
+ try { localStorage.setItem(THEME_KEY, t); } catch (e) {}
890
+ const isNight = t === "night";
891
+ document.getElementById("themeIcon").textContent = isNight ? "\uD83C\uDF19" : "\uD83C\uDF1E";
892
+ document.getElementById("themeLabel").textContent = isNight ? "Night at home" : "Day at school";
893
+ }
894
+ (function initTheme() {
895
+ try {
896
+ const s = localStorage.getItem(THEME_KEY);
897
+ if (s === "day" || s === "night") { setTheme(s); return; }
898
+ } catch (e) {}
899
+ })();
900
+ document.getElementById("btnTheme").addEventListener("click", function () {
901
+ const cur = document.documentElement.getAttribute("data-theme") || "day";
902
+ setTheme(cur === "day" ? "night" : "day");
903
+ });
904
+
905
+ function updateLayoutClass() {
906
+ const play = document.getElementById("playCard");
907
+ const m = document.getElementById("mainLayout");
908
+ m.classList.toggle("has-play", play.style.display !== "none" && getComputedStyle(play).display !== "none");
909
+ }
910
+
911
+ async function mcp(method, params) {
912
+ const r = await fetch(API("/mcp"), {
913
+ method: "POST",
914
+ headers: { "Content-Type": "application/json" },
915
+ body: JSON.stringify({ jsonrpc: "2.0", method, params: params || {}, id: nextId() }),
916
+ });
917
+ if (!r.ok) throw new Error("HTTP " + r.status);
918
+ const j = await r.json();
919
+ if (j.error) throw new Error(j.error.message || String(j.error));
920
+ return j;
921
+ }
922
+
923
+ function unwrapResult(j) {
924
+ const r = j.result;
925
+ if (!r) return null;
926
+ if (r.structuredContent && typeof r.structuredContent === "object") return r.structuredContent;
927
+ if (r.data && typeof r.data === "object") return r.data;
928
+ if (Array.isArray(r.content) && r.content[0] && r.content[0].text) {
929
+ try { return JSON.parse(r.content[0].text); } catch { return { raw: r.content[0].text }; }
930
+ }
931
+ if (r && typeof r === "object" && !r.content) return r;
932
+ return r;
933
+ }
934
+
935
+ async function toolCall(name, args) {
936
+ const j = await mcp("tools/call", {
937
+ session_id: sessionId,
938
+ name,
939
+ arguments: args || {},
940
+ });
941
+ return unwrapResult(j);
942
+ }
943
+
944
+ function showOops(visible) {
945
+ const c = document.getElementById("chibi");
946
+ const s = document.getElementById("oopsSticker");
947
+ if (visible) {
948
+ c.classList.add("oops");
949
+ if (s) {
950
+ s.classList.remove("oops-bump");
951
+ void s.offsetWidth;
952
+ s.classList.add("oops-bump");
953
+ if (s._oopsBumpT) clearTimeout(s._oopsBumpT);
954
+ s._oopsBumpT = setTimeout(function () {
955
+ s.classList.remove("oops-bump");
956
+ s._oopsBumpT = 0;
957
+ }, 600);
958
+ }
959
+ } else {
960
+ c.classList.remove("oops");
961
+ if (s) {
962
+ s.classList.remove("oops-bump");
963
+ if (s._oopsBumpT) clearTimeout(s._oopsBumpT);
964
+ }
965
+ }
966
+ }
967
+
968
+ function burstConfetti() {
969
+ const host = document.getElementById("confetti");
970
+ host.innerHTML = "";
971
+ const n = 28;
972
+ for (let i = 0; i < n; i++) {
973
+ const el = document.createElement("i");
974
+ el.style.left = (Math.random() * 100) + "%";
975
+ el.style.background = "hsl(" + (30 + Math.random() * 280) + ", 90%, 55%)";
976
+ el.style.animationDelay = (Math.random() * 0.4) + "s";
977
+ el.style.animationDuration = (2 + Math.random() * 1) + "s";
978
+ host.appendChild(el);
979
+ }
980
+ setTimeout(function () { host.innerHTML = ""; }, 3200);
981
+ }
982
+
983
+ function renderScenario(data) {
984
+ if (data.error) throw new Error(data.error);
985
+ lastScenario = data;
986
+ const scene = document.getElementById("sceneCard");
987
+ scene.classList.remove("in-view");
988
+ void scene.offsetWidth;
989
+ scene.classList.add("in-view");
990
+ document.getElementById("sceneTitle").textContent = data.title || "Scenario";
991
+ document.getElementById("sceneNarrative").textContent = data.narrative || "";
992
+ const pills = document.getElementById("charPills");
993
+ pills.innerHTML = (data.characters_involved || [])
994
+ .map(function (c) { return '<span class="pill">' + escapeHtml(c.name) + "</span>"; })
995
+ .join(" ");
996
+ const list = document.getElementById("actionList");
997
+ list.className = "actions stagger-children";
998
+ list.innerHTML = (data.available_actions || []).map(function (a, i) {
999
+ return (
1000
+ '<button type="button" class="act-btn" style="--st:' + i + '" data-name="' + escapeAttr(a.name) + '">' +
1001
+ '<div class="act-name">' + escapeHtml(a.name) + "</div>" +
1002
+ '<div class="act-desc">' + escapeHtml(a.description) + "</div></button>"
1003
+ );
1004
+ }).join("");
1005
+ list.querySelectorAll(".act-btn").forEach(function (btn) {
1006
+ btn.addEventListener("click", function () {
1007
+ selectedAction = btn.getAttribute("data-name");
1008
+ list.querySelectorAll(".act-btn").forEach(function (b) { b.setAttribute("aria-pressed", "false"); });
1009
+ btn.setAttribute("aria-pressed", "true");
1010
+ document.getElementById("btnAct").disabled = false;
1011
+ });
1012
+ });
1013
+ document.getElementById("sceneCard").style.display = "block";
1014
+ document.getElementById("playCard").style.display = "block";
1015
+ updateLayoutClass();
1016
+ }
1017
+
1018
+ function escapeHtml(s) {
1019
+ if (!s) return "";
1020
+ return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1021
+ }
1022
+ function escapeAttr(s) { return String(s).replace(/"/g, "&quot;"); }
1023
+
1024
+ function renderResult(res) {
1025
+ const body = document.getElementById("resultBody");
1026
+ document.getElementById("resultCard").style.display = "block";
1027
+ const total = Number(res.reward || 0);
1028
+ const rc = res.reward_components || {};
1029
+ const dq = rc.decision_quality;
1030
+ const mistake = (total < 0.32) || (typeof dq === "number" && dq < 0.45);
1031
+ showOops(!!mistake);
1032
+ if (mistake) {
1033
+ document.body.classList.add("shake");
1034
+ setTimeout(function () { document.body.classList.remove("shake"); }, 500);
1035
+ } else {
1036
+ if (total >= 0.5) burstConfetti();
1037
+ }
1038
+
1039
+ const pct = Math.max(0, Math.min(100, (total + 0.5) * 100));
1040
+ const lines = (res.consequences || "").split("\n").filter(Boolean);
1041
+ const speech = (res.shinchan_said || "").trim();
1042
+ let html = "";
1043
+ if (mistake) {
1044
+ html += '<div class="melt-banner">Classic chaos — the universe is taking notes.</div>';
1045
+ } else {
1046
+ html += '<div class="speech win"><strong>Shin-chan said:</strong> ' + escapeHtml(speech) + "</div>";
1047
+ }
1048
+ if (mistake && speech) {
1049
+ html += '<div class="speech"><strong>Still blurted:</strong> ' + escapeHtml(speech) + "</div>";
1050
+ }
1051
+ lines.forEach(function (line) {
1052
+ html += '<div class="speech">' + escapeHtml(line) + "</div>";
1053
+ });
1054
+ html +=
1055
+ '<div class="meter"><span>Score</span><div class="bar"><div class="fill" style="width:' +
1056
+ pct +
1057
+ '%"></div></div><span class="score-num">' +
1058
+ total.toFixed(2) +
1059
+ "</span></div>";
1060
+ html += '<div class="score-grid">';
1061
+ for (const [k, v] of Object.entries(rc)) {
1062
+ if (k === "total") continue;
1063
+ if (typeof v === "number") {
1064
+ html += "<div><strong>" + escapeHtml(k) + "</strong><br />" + v.toFixed(2) + "</div>";
1065
+ }
1066
+ }
1067
+ html += "</div>";
1068
+ if (res.status) {
1069
+ html += '<p class="status">' + escapeHtml(res.status) + "</p>";
1070
+ }
1071
+ body.innerHTML = html;
1072
+ }
1073
+
1074
+ function initialsFromName(name) {
1075
+ if (!name) return "?";
1076
+ const p = String(name).split(/\s+/);
1077
+ if (p.length === 1) return p[0].slice(0, 2).toUpperCase();
1078
+ return (p[0][0] + p[1][0]).toUpperCase();
1079
+ }
1080
+
1081
+ async function loadRelationships() {
1082
+ const d = (await toolCall("get_relationships", {})) || {};
1083
+ const el = document.getElementById("relBody");
1084
+ const relCard = document.getElementById("relCard");
1085
+ if (d.status) {
1086
+ el.textContent = d.status;
1087
+ relCard.style.display = "block";
1088
+ return;
1089
+ }
1090
+ const keys = Object.keys(d).filter(function (k) { return d[k] && d[k].name; });
1091
+ if (!keys.length) {
1092
+ relCard.style.display = "none";
1093
+ return;
1094
+ }
1095
+ el.innerHTML = keys
1096
+ .map(function (k) {
1097
+ const r = d[k];
1098
+ const v = Math.max(0, Math.min(1, Number(r.value) || 0)) * 100;
1099
+ return (
1100
+ '<div class="rel-row"><span class="rel-avatar" title="' +
1101
+ escapeAttr(r.name) +
1102
+ '">' +
1103
+ initialsFromName(r.name) +
1104
+ '</span><span style="min-width:5rem;">' +
1105
+ escapeHtml(r.name) +
1106
+ '</span><div class="rel-bar-wrap"><div class="rel-bar" style="width:' +
1107
+ v +
1108
+ '%"></div></div><span class="num">' +
1109
+ (typeof r.value === "number" ? r.value.toFixed(2) : "") +
1110
+ "</span></div>"
1111
+ );
1112
+ })
1113
+ .join("");
1114
+ relCard.style.display = "block";
1115
+ }
1116
+
1117
+ document.getElementById("btnStart").addEventListener("click", async function () {
1118
+ const st = document.getElementById("setupStatus");
1119
+ st.textContent = "Connecting…";
1120
+ st.classList.remove("err");
1121
+ showOops(false);
1122
+ try {
1123
+ const c1 = await mcp("openenv/session/create", {});
1124
+ const sinfo = unwrapResult(c1) || c1.result || {};
1125
+ sessionId = sinfo.session_id || (c1.result && c1.result.session_id);
1126
+ if (!sessionId) throw new Error("No session_id");
1127
+ await toolCall("new_episode", {});
1128
+ const sc = await toolCall("get_scenario_info", {});
1129
+ selectedAction = null;
1130
+ document.getElementById("btnAct").disabled = true;
1131
+ renderScenario(sc);
1132
+ st.textContent = "You’re in — make it legendary (or a disaster).";
1133
+ document.getElementById("resultCard").style.display = "none";
1134
+ document.getElementById("resultBody").innerHTML = "";
1135
+ await loadRelationships();
1136
+ } catch (e) {
1137
+ st.textContent = String((e && e.message) || e);
1138
+ st.classList.add("err");
1139
+ }
1140
+ });
1141
+
1142
+ document.getElementById("btnAct").addEventListener("click", async function () {
1143
+ if (!selectedAction || !sessionId) return;
1144
+ const st = document.getElementById("actStatus");
1145
+ st.textContent = "Doing the thing…";
1146
+ st.classList.remove("err");
1147
+ showOops(false);
1148
+ try {
1149
+ const res = await toolCall("choose_action", {
1150
+ action_name: selectedAction,
1151
+ reasoning: document.getElementById("reasoning").value || "I did my best, maybe.",
1152
+ dialogue: document.getElementById("dialogue").value || "Buri buri~!",
1153
+ });
1154
+ if (res.error) throw new Error(res.error);
1155
+ renderResult(res);
1156
+ await loadRelationships();
1157
+ if (res.done) {
1158
+ st.textContent = "That’s a wrap. Hit “Start / new episode” for round two.";
1159
+ document.getElementById("btnAct").disabled = true;
1160
+ } else {
1161
+ st.textContent = "Locked in. What’s the next move?";
1162
+ }
1163
+ const g = await toolCall("get_scenario_info", {});
1164
+ if (g && !g.error) renderScenario(g);
1165
+ } catch (e) {
1166
+ st.textContent = String((e && e.message) || e);
1167
+ st.classList.add("err");
1168
+ }
1169
+ });
1170
+
1171
+ document.getElementById("btnRescan").addEventListener("click", function () {
1172
+ loadRelationships().catch(function () {});
1173
+ });
1174
+ </script>
1175
+ </body>
1176
+ </html>
tests/test_smoke.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+
4
+ from fastapi.testclient import TestClient
5
+ from openenv.core.env_server.mcp_types import CallToolAction
6
+
7
+ from sinchan_env import CallToolEnv, SinChanEnv
8
+ from server.app import app
9
+ from server.scenario_data import ALL_SCENARIOS
10
+ from server.sinchan_environment import SinChanEnvironment
11
+
12
+
13
+ def _obs_result(obs):
14
+ result = getattr(obs, "result", None)
15
+ if isinstance(result, dict):
16
+ return result
17
+
18
+ content = getattr(result, "content", None)
19
+ if isinstance(content, list) and content:
20
+ text = getattr(content[0], "text", "")
21
+ if isinstance(text, str) and text:
22
+ try:
23
+ return json.loads(text)
24
+ except json.JSONDecodeError:
25
+ return {"raw": text}
26
+
27
+ return {}
28
+
29
+
30
+ def test_scenario_count_minimum():
31
+ assert len(ALL_SCENARIOS) >= 30
32
+
33
+
34
+ def test_health_endpoint_available():
35
+ response = TestClient(app).get("/health")
36
+ assert response.status_code == 200
37
+ payload = response.json()
38
+ assert payload.get("status") in {"ok", "healthy"}
39
+
40
+
41
+ def test_blog_md_endpoint_available():
42
+ response = TestClient(app).get("/blog.md")
43
+ assert response.status_code == 200
44
+ text = response.text
45
+ assert "Shin-chan" in text or "blog" in text.lower()
46
+
47
+
48
+ def test_http_mcp_preflight_contract_matches_script():
49
+ """Same JSON-RPC sequence as training/preflight_space.py (no WebSocket)."""
50
+ c = TestClient(app)
51
+ assert c.get("/health").status_code == 200
52
+ assert c.post("/reset", json={}).status_code == 200
53
+
54
+ r1 = c.post(
55
+ "/mcp",
56
+ json={"jsonrpc": "2.0", "method": "openenv/session/create", "params": {}, "id": 1},
57
+ )
58
+ assert r1.status_code == 200
59
+ data1 = r1.json()
60
+ assert "error" not in data1
61
+ session_id = (data1.get("result") or {}).get("session_id")
62
+ assert session_id
63
+
64
+ r2 = c.post(
65
+ "/mcp",
66
+ json={
67
+ "jsonrpc": "2.0",
68
+ "method": "tools/list",
69
+ "params": {"session_id": session_id},
70
+ "id": 2,
71
+ },
72
+ )
73
+ assert r2.status_code == 200
74
+ data2 = r2.json()
75
+ assert "error" not in data2
76
+ tools = (data2.get("result") or {}).get("tools") or []
77
+ names = [t.get("name") for t in tools if isinstance(t, dict)]
78
+ assert "get_scenario_info" in names
79
+ assert "new_episode" in names
80
+
81
+ r_ne = c.post(
82
+ "/mcp",
83
+ json={
84
+ "jsonrpc": "2.0",
85
+ "method": "tools/call",
86
+ "params": {
87
+ "session_id": session_id,
88
+ "name": "new_episode",
89
+ "arguments": {},
90
+ },
91
+ "id": 3,
92
+ },
93
+ )
94
+ assert r_ne.status_code == 200
95
+ assert "error" not in r_ne.json()
96
+
97
+ r3 = c.post(
98
+ "/mcp",
99
+ json={
100
+ "jsonrpc": "2.0",
101
+ "method": "tools/call",
102
+ "params": {
103
+ "session_id": session_id,
104
+ "name": "get_scenario_info",
105
+ "arguments": {},
106
+ },
107
+ "id": 4,
108
+ },
109
+ )
110
+ assert r3.status_code == 200
111
+ data3 = r3.json()
112
+ assert "error" not in data3
113
+ ginfo = (data3.get("result") or {}).get("data") or {}
114
+ if not ginfo.get("title") and (data3.get("result") or {}).get("structuredContent"):
115
+ ginfo = (data3.get("result") or {})["structuredContent"]
116
+ assert ginfo.get("title"), f"get_scenario_info should return a title, got: {ginfo!r}"
117
+
118
+
119
+ def test_package_exports_calltoolenv_alias():
120
+ assert CallToolEnv.__name__ == "CallToolEnv"
121
+ assert issubclass(CallToolEnv, SinChanEnv)
122
+
123
+
124
+ def test_calltoolenv_http_mode_maps_step_to_call_tool():
125
+ env = CallToolEnv(base_url="http://localhost:8000", prefer_http_mcp=True)
126
+
127
+ async def fake_call_tool(name, **kwargs):
128
+ return {"reward": 0.25, "done": True, "reward_components": {"total": 0.25}}
129
+
130
+ env.call_tool = fake_call_tool # type: ignore[method-assign]
131
+ result = asyncio.run(
132
+ env.step(CallToolAction(tool_name="choose_action", arguments={}))
133
+ )
134
+
135
+ assert result.reward == 0.25
136
+ assert result.done is True
137
+ assert result.observation.metadata.get("total") == 0.25
138
+
139
+
140
+ def test_reset_and_get_scenario_info():
141
+ env = SinChanEnvironment()
142
+ env.reset(seed=123)
143
+
144
+ info_obs = env.step(CallToolAction(tool_name="get_scenario_info", arguments={}))
145
+ info = _obs_result(info_obs)
146
+
147
+ assert isinstance(info, dict)
148
+ assert info.get("title")
149
+ assert isinstance(info.get("available_actions"), list)
150
+ assert len(info["available_actions"]) > 0
151
+
152
+
153
+ def test_choose_action_reward_and_episode_completion():
154
+ env = SinChanEnvironment()
155
+ env.reset(seed=456)
156
+
157
+ info_obs = env.step(CallToolAction(tool_name="get_scenario_info", arguments={}))
158
+ info = _obs_result(info_obs)
159
+ action_name = info["available_actions"][0]["name"]
160
+
161
+ done = False
162
+ steps = 0
163
+
164
+ while not done and steps < 10:
165
+ step_obs = env.step(
166
+ CallToolAction(
167
+ tool_name="choose_action",
168
+ arguments={
169
+ "action_name": action_name,
170
+ "reasoning": "I should think about tomorrow and family feelings.",
171
+ "dialogue": "Buri buri~ I will do my best!",
172
+ },
173
+ )
174
+ )
175
+ step_result = _obs_result(step_obs)
176
+
177
+ assert -0.5 <= step_obs.reward <= 1.0
178
+ assert isinstance(step_result.get("reward"), (int, float))
179
+ assert isinstance(step_result.get("reward_components"), dict)
180
+ assert isinstance(step_result.get("done"), bool)
181
+ done = bool(step_obs.done)
182
+ steps += 1
183
+
184
+ assert done
185
+ assert steps > 0
training/ShinChan_GRPO_Training.ipynb ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# 🖍️ ShinChan Life Simulator - GRPO Training with OpenEnv\n",
8
+ "Train a small language model to make decisions as Shin-chan using Reinforcement Learning!"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "metadata": {},
14
+ "source": [
15
+ "# Bootstrap repo + dependencies (robust Colab setup)\n",
16
+ "import os\n",
17
+ "import subprocess\n",
18
+ "import sys\n",
19
+ "from pathlib import Path\n",
20
+ "\n",
21
+ "REPO_URL = \"https://github.com/Sarthaks-24/sinchan_env.git\"\n",
22
+ "REPO_DIR = Path(\"/content/sinchan_env\")\n",
23
+ "\n",
24
+ "# 1) Core dependencies\n",
25
+ "# transform>=5.2 + jmespath: TRL GRPOTrainer with OpenEnv (environment_factory)\n",
26
+ "subprocess.check_call([\n",
27
+ " sys.executable,\n",
28
+ " \"-m\",\n",
29
+ " \"pip\",\n",
30
+ " \"install\",\n",
31
+ " \"-q\",\n",
32
+ " \"openenv-core[core]>=0.2.3\",\n",
33
+ " \"trl\",\n",
34
+ " \"datasets\",\n",
35
+ " \"torch\",\n",
36
+ " \"transformers>=5.2.0\",\n",
37
+ " \"jmespath\",\n",
38
+ " \"matplotlib\",\n",
39
+ "])\n",
40
+ "\n",
41
+ "# 2) Ensure repository exists in /content (and refresh if already cloned)\n",
42
+ "if not REPO_DIR.exists():\n",
43
+ " subprocess.check_call([\"git\", \"clone\", REPO_URL, str(REPO_DIR)])\n",
44
+ "else:\n",
45
+ " # Keep Colab copy synced with latest fixes from the repo.\n",
46
+ " subprocess.check_call([\"git\", \"-C\", str(REPO_DIR), \"pull\", \"--ff-only\"])\n",
47
+ "\n",
48
+ "# 3) Validate project root and editable install\n",
49
+ "if not (REPO_DIR / \"pyproject.toml\").exists():\n",
50
+ " raise FileNotFoundError(f\"pyproject.toml not found at {REPO_DIR}. Check REPO_URL.\")\n",
51
+ "\n",
52
+ "subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-e\", str(REPO_DIR)])\n",
53
+ "os.chdir(REPO_DIR)\n",
54
+ "\n",
55
+ "print(\"Repository:\", REPO_DIR)\n",
56
+ "print(\"Working dir:\", os.getcwd())\n",
57
+ "print(\"Setup complete.\")"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "markdown",
64
+ "metadata": {},
65
+ "source": [
66
+ "### Step 1: Connect to the Environment\n",
67
+ "**`ENV_URL` (next cell) must be the Space *runtime* host, not the Hugging Face repo page.** Use the URL that loads the OpenEnv Playground in your browser (base URL only, no `/web`).\n",
68
+ "\n",
69
+ "- **Default in this repo:** `https://gladiator-codes-sinchan-env-a446abd.hf.space` — this is a **revision** host; it may work when the short `https://gladiator-codes-sinchan-env.hf.space` shows \"space in error\" (Hub routing). After a **rebuild**, the `‑a446abd` segment can change: if probes fail, copy the new base URL from the working Playground.\n",
70
+ "- **Optional (recommended):** `python training/preflight_space.py --base-url <ENV_URL> --retries 3` after `cd` to the repo — checks `/health`, `POST /reset`, and `POST /mcp` without WebSockets.\n",
71
+ "\n",
72
+ "Use `from sinchan_env import SinChanEnv` (not `from openenv import CallToolEnv` unless your version has it). Playground snippets with `CallToolAction(message=...)` do not match this project’s tools.\n",
73
+ "\n",
74
+ "**Fallback:** if the remote host stays down, the next cell can fall back to a local server on `http://127.0.0.1:8000`."
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "import os\n",
82
+ "# Runtime base URL (no /web) — use the host that actually loads the Playground; revision hosts often work when the short *.hf.space URL is in error\n",
83
+ "os.environ[\"ENV_URL\"] = \"https://gladiator-codes-sinchan-env-a446abd.hf.space\"\n",
84
+ "print(\"ENV_URL:\", os.environ[\"ENV_URL\"])"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# Connectivity probe with permanent fallback:\n",
94
+ "# 1) Try HF Space using HTTP health + HTTP MCP tool calls (no websocket dependency)\n",
95
+ "# 2) If unstable, auto-start local server in Colab and continue on localhost\n",
96
+ "import os\n",
97
+ "import time\n",
98
+ "import subprocess\n",
99
+ "import sys\n",
100
+ "from pathlib import Path\n",
101
+ "\n",
102
+ "import requests\n",
103
+ "from sinchan_env import SinChanEnv\n",
104
+ "\n",
105
+ "\n",
106
+ "def probe_env(base_url: str, attempts: int = 15):\n",
107
+ " \"\"\"Try HTTP health + HTTP MCP list/get_scenario_info with retries.\n",
108
+ "\n",
109
+ " HF free-tier Spaces often return 503 for 1–3+ minutes while cold; we wake\n",
110
+ " the route with GET / and GET /web before /health, and wait longer on 503.\n",
111
+ " \"\"\"\n",
112
+ " base = base_url.rstrip(\"/\")\n",
113
+ " health_url = f\"{base}/health\"\n",
114
+ " last_err = None\n",
115
+ "\n",
116
+ " for idx in range(1, attempts + 1):\n",
117
+ " try:\n",
118
+ " # Wake proxy + container (Gradio and root often return 200 before /health is ready)\n",
119
+ " for wake_path in (\"/\", \"/web\"):\n",
120
+ " try:\n",
121
+ " w = requests.get(f\"{base}{wake_path}\", timeout=30, allow_redirects=True)\n",
122
+ " print(f\" (wake) GET {wake_path} -> {w.status_code}\")\n",
123
+ " except Exception as wexc:\n",
124
+ " print(f\" (wake) GET {wake_path} -> {wexc}\")\n",
125
+ "\n",
126
+ " r = requests.get(health_url, timeout=30)\n",
127
+ " if r.status_code == 503:\n",
128
+ " # Cold start: wait longer than a few seconds\n",
129
+ " wait_503 = min(120, 20 + 15 * idx)\n",
130
+ " print(\n",
131
+ " f\"[Probe {idx}/{attempts}] /health -> 503 (Space waking or building). \"\n",
132
+ " f\"Waiting {wait_503}s... Open the Space in a browser tab to speed wake.\"\n",
133
+ " )\n",
134
+ " time.sleep(wait_503)\n",
135
+ " continue\n",
136
+ " if r.status_code != 200:\n",
137
+ " raise RuntimeError(f\"health check returned {r.status_code}\")\n",
138
+ "\n",
139
+ " # Prefer HTTP MCP mode for hosted environments.\n",
140
+ " client = SinChanEnv(base_url=base, prefer_http_mcp=True)\n",
141
+ " sync_ctx = client.sync() if hasattr(client, \"sync\") else client\n",
142
+ " with sync_ctx as env:\n",
143
+ " requests.post(f\"{base}/reset\", json={}, timeout=30).raise_for_status()\n",
144
+ " env.list_tools(use_cache=False)\n",
145
+ " info = env.call_tool(\"get_scenario_info\")\n",
146
+ " title = info.get(\"title\", \"unknown\") if isinstance(info, dict) else \"unknown\"\n",
147
+ " print(f\"Probe OK at {base_url}. Scenario: {title}\")\n",
148
+ " return True, None\n",
149
+ " except Exception as exc:\n",
150
+ " last_err = exc\n",
151
+ " wait = min(90, 10 * idx)\n",
152
+ " print(f\"[Probe retry {idx}/{attempts}] {base_url} not ready, waiting {wait}s... Error: {exc}\")\n",
153
+ " time.sleep(wait)\n",
154
+ "\n",
155
+ " return False, last_err\n",
156
+ "\n",
157
+ "\n",
158
+ "def start_local_server() -> subprocess.Popen:\n",
159
+ " \"\"\"Start uvicorn server in background inside Colab.\"\"\"\n",
160
+ " repo_dir = Path(\"/content/sinchan_env\")\n",
161
+ "\n",
162
+ " env_vars = os.environ.copy()\n",
163
+ " env_vars[\"ENABLE_WEB_INTERFACE\"] = \"false\"\n",
164
+ "\n",
165
+ " cmd = [\n",
166
+ " sys.executable,\n",
167
+ " \"-m\",\n",
168
+ " \"uvicorn\",\n",
169
+ " \"server.app:app\",\n",
170
+ " \"--host\",\n",
171
+ " \"0.0.0.0\",\n",
172
+ " \"--port\",\n",
173
+ " \"8000\",\n",
174
+ " ]\n",
175
+ " print(\"Starting local fallback server:\", \" \".join(cmd))\n",
176
+ " proc = subprocess.Popen(\n",
177
+ " cmd,\n",
178
+ " cwd=str(repo_dir),\n",
179
+ " env=env_vars,\n",
180
+ " stdout=sys.stdout,\n",
181
+ " stderr=sys.stderr,\n",
182
+ " )\n",
183
+ "\n",
184
+ " local_health = \"http://127.0.0.1:8000/health\"\n",
185
+ " for _ in range(30):\n",
186
+ " try:\n",
187
+ " r = requests.get(local_health, timeout=2)\n",
188
+ " if r.status_code == 200:\n",
189
+ " print(\"Local server is healthy at\", local_health)\n",
190
+ " return proc\n",
191
+ " except Exception:\n",
192
+ " pass\n",
193
+ " time.sleep(1)\n",
194
+ "\n",
195
+ " proc.terminate()\n",
196
+ " raise RuntimeError(\"Local fallback server failed to start on :8000\")\n",
197
+ "\n",
198
+ "\n",
199
+ "remote_url = os.environ[\"ENV_URL\"].rstrip(\"/\")\n",
200
+ "print(\"Primary ENV_URL:\", remote_url)\n",
201
+ "\n",
202
+ "ok, err = probe_env(remote_url, attempts=15)\n",
203
+ "\n",
204
+ "if not ok:\n",
205
+ " print(\"Remote Space unstable. Switching to local fallback for training.\")\n",
206
+ " _local_server_proc = start_local_server()\n",
207
+ " os.environ[\"ENV_URL\"] = \"http://127.0.0.1:8000\"\n",
208
+ " print(\"ENV_URL switched to\", os.environ[\"ENV_URL\"])\n",
209
+ " ok2, err2 = probe_env(os.environ[\"ENV_URL\"], attempts=20)\n",
210
+ " if not ok2:\n",
211
+ " raise RuntimeError(f\"Both remote and local probes failed. Remote error: {err}; Local error: {err2}\")\n"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "metadata": {},
219
+ "source": [
220
+ "### (Optional) Stages 1 & 2 before full training\n",
221
+ "\n",
222
+ "- **Stage 1** — `stage1_validate_env.py`: random agent, prints rewards (confirms the Space is usable).\n",
223
+ "- **Stage 2** — `stage2_minimal_train.py`: very short GRPO (delegates to `train_sinchan.py`).\n",
224
+ "\n",
225
+ "If you use **QLoRA**, run the next cell to install `peft` and `bitsandbytes`, then add `--use-qlora` to the training command in Step 2 (GPU only)."
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "metadata": {},
231
+ "source": [
232
+ "# Optional: QLoRA deps (GPU). Safe to skip for full-finetune-style run on small Qwen3-0.6B.\n",
233
+ "import subprocess\n",
234
+ "import sys\n",
235
+ "USE_QLORA = False # set True + add --use-qlora to training cmd in the next section\n",
236
+ "if USE_QLORA:\n",
237
+ " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"peft\", \"bitsandbytes\"])"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Optional — Stage 1: environment validation (random policy)\n",
247
+ "import os, subprocess, sys\n",
248
+ "S1 = \"/content/sinchan_env/training/stage1_validate_env.py\"\n",
249
+ "if os.path.exists(S1):\n",
250
+ " subprocess.check_call([sys.executable, S1, \"--env-url\", os.environ[\"ENV_URL\"]])\n",
251
+ "else:\n",
252
+ " print(\"Skip: stage1_validate_env.py not in repo path yet.\")"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "markdown",
259
+ "metadata": {},
260
+ "source": [
261
+ "### Step 2: Run Training (Configurable)"
262
+ ]
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Run training with explicit args for reproducibility\n",
269
+ "# NOTE: Do NOT use capture_output=True here — long GRPO runs would show *no* live logs and look \"frozen\"\n",
270
+ "# (then Colab interrupt shows as KeyboardInterrupt in subprocess internals). Stream to the cell instead.\n",
271
+ "import os\n",
272
+ "import subprocess\n",
273
+ "import sys\n",
274
+ "\n",
275
+ "TRAIN_SCRIPT = \"/content/sinchan_env/training/train_sinchan.py\"\n",
276
+ "OUTPUT_DIR = \"/content/sinchan_env/training/artifacts/run1\"\n",
277
+ "# Set True for a 1–2 min sanity check (tiny steps). Set False for the full assignment run.\n",
278
+ "SMOKE_TEST = False\n",
279
+ "\n",
280
+ "if not os.path.exists(TRAIN_SCRIPT):\n",
281
+ " raise FileNotFoundError(f\"Training script not found: {TRAIN_SCRIPT}\")\n",
282
+ "\n",
283
+ "if SMOKE_TEST:\n",
284
+ " max_steps, dataset_size = \"3\", \"4\"\n",
285
+ " print(\"SMOKE_TEST=True: using --max-steps 3 and --dataset-size 4. Set SMOKE_TEST=False for full training.\")\n",
286
+ "else:\n",
287
+ " max_steps, dataset_size = \"200\", \"200\"\n",
288
+ " if os.environ.get(\"COLAB_RELEASE_TAG\"):\n",
289
+ " print(\n",
290
+ " \"Tip: With --precision auto, if you see use_cpu=True training will be *very* slow. \"\n",
291
+ " \"Use Runtime -> Change runtime type -> GPU, then re-run from the top.\"\n",
292
+ " )\n",
293
+ "\n",
294
+ "cmd = [\n",
295
+ " sys.executable,\n",
296
+ " TRAIN_SCRIPT,\n",
297
+ " \"--env-url\", os.environ[\"ENV_URL\"],\n",
298
+ " \"--model\", \"Qwen/Qwen3-0.6B\",\n",
299
+ " \"--precision\", \"auto\",\n",
300
+ " \"--max-steps\", max_steps,\n",
301
+ " \"--dataset-size\", dataset_size,\n",
302
+ " \"--learning-rate\", \"1e-5\",\n",
303
+ " \"--num-generations\", \"2\",\n",
304
+ " \"--output-dir\", OUTPUT_DIR,\n",
305
+ "]\n",
306
+ "# Set True with GPU + peft/bitsandbytes installed (see QLoRA cell)\n",
307
+ "USE_QLORA = False\n",
308
+ "if USE_QLORA:\n",
309
+ " cmd.append(\"--use-qlora\")\n",
310
+ "print(\"Running (streaming logs below):\", \" \".join(cmd))\n",
311
+ "env = os.environ.copy()\n",
312
+ "env.setdefault(\"PYTHONUNBUFFERED\", \"1\")\n",
313
+ "rc = subprocess.run(cmd, env=env).returncode\n",
314
+ "if rc != 0:\n",
315
+ " raise RuntimeError(\n",
316
+ " f\"Training exited with code {rc}. Scroll *up* in this cell for the Python traceback and tqdm output.\"\n",
317
+ " )\n",
318
+ "print(\"Done. Artifacts under:\", OUTPUT_DIR)"
319
+ ],
320
+ "execution_count": null,
321
+ "outputs": []
322
+ },
323
+ {
324
+ "cell_type": "markdown",
325
+ "metadata": {},
326
+ "source": [
327
+ "### Step 3: Generate Evaluation Summary\n",
328
+ "Run a quick baseline comparison and save JSON evidence."
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "source": [
335
+ "import os\n",
336
+ "import subprocess\n",
337
+ "import sys\n",
338
+ "\n",
339
+ "EVAL_SCRIPT = \"/content/sinchan_env/training/evaluate_scenarios.py\"\n",
340
+ "EVAL_OUTPUT = \"/content/sinchan_env/training/artifacts/eval_summary.json\"\n",
341
+ "\n",
342
+ "if not os.path.exists(EVAL_SCRIPT):\n",
343
+ " raise FileNotFoundError(f\"Eval script not found: {EVAL_SCRIPT}\")\n",
344
+ "\n",
345
+ "cmd = [\n",
346
+ " sys.executable,\n",
347
+ " EVAL_SCRIPT,\n",
348
+ " \"--env-url\", os.environ[\"ENV_URL\"],\n",
349
+ " \"--episodes\", \"10\",\n",
350
+ " \"--output\", EVAL_OUTPUT,\n",
351
+ "]\n",
352
+ "print(\"Running:\", \" \".join(cmd))\n",
353
+ "rc = subprocess.run(cmd).returncode\n",
354
+ "if rc != 0:\n",
355
+ " raise RuntimeError(f\"Eval exited with code {rc}. Scroll up for script output.\")"
356
+ ],
357
+ "execution_count": null,
358
+ "outputs": []
359
+ },
360
+ {
361
+ "cell_type": "markdown",
362
+ "metadata": {},
363
+ "source": [
364
+ "### Step 4: Generate Plot PNGs for Submission\n",
365
+ "Creates reward/loss/baseline comparison charts in `assets/`."
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "code",
370
+ "metadata": {},
371
+ "source": [
372
+ "import os\n",
373
+ "import subprocess\n",
374
+ "import sys\n",
375
+ "\n",
376
+ "PLOT_SCRIPT = \"/content/sinchan_env/training/plot_metrics.py\"\n",
377
+ "RUN_DIR = \"/content/sinchan_env/training/artifacts/run1\"\n",
378
+ "EVAL_SUMMARY = \"/content/sinchan_env/training/artifacts/eval_summary.json\"\n",
379
+ "ASSETS_DIR = \"/content/sinchan_env/assets\"\n",
380
+ "\n",
381
+ "if not os.path.exists(PLOT_SCRIPT):\n",
382
+ " raise FileNotFoundError(f\"Plot script not found: {PLOT_SCRIPT}\")\n",
383
+ "\n",
384
+ "cmd = [\n",
385
+ " sys.executable,\n",
386
+ " PLOT_SCRIPT,\n",
387
+ " \"--run-dir\", RUN_DIR,\n",
388
+ " \"--eval-summary\", EVAL_SUMMARY,\n",
389
+ " \"--assets-dir\", ASSETS_DIR,\n",
390
+ "]\n",
391
+ "print(\"Running:\", \" \".join(cmd))\n",
392
+ "rc = subprocess.run(cmd).returncode\n",
393
+ "if rc != 0:\n",
394
+ " raise RuntimeError(f\"Plotting exited with code {rc}. Scroll up for script output.\")"
395
+ ],
396
+ "execution_count": null,
397
+ "outputs": []
398
+ }
399
+ ],
400
+ "metadata": {
401
+ "kernelspec": {
402
+ "display_name": "openenv-sinchan-env (3.13.9)",
403
+ "language": "python",
404
+ "name": "python3"
405
+ },
406
+ "language_info": {
407
+ "codemirror_mode": {
408
+ "name": "ipython",
409
+ "version": 3
410
+ },
411
+ "file_extension": ".py",
412
+ "mimetype": "text/x-python",
413
+ "name": "python",
414
+ "nbconvert_exporter": "python",
415
+ "pygments_lexer": "ipython3",
416
+ "version": "3.13.9"
417
+ }
418
+ },
419
+ "nbformat": 4,
420
+ "nbformat_minor": 4
421
+ }
training/evaluate_scenarios.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import random
4
+ import time
5
+ from pathlib import Path
6
+
7
+ from openenv.core.env_server.mcp_types import CallToolAction
8
+
9
+ from sinchan_env import SinChanEnv
10
+
11
+
12
+ def _random_agent_choice(actions: list[dict]) -> tuple[str, str, str]:
13
+ action = random.choice(actions)
14
+ return (
15
+ action["name"],
16
+ "Random baseline: selecting an arbitrary action.",
17
+ "Buri buri~ I'm doing something random!",
18
+ )
19
+
20
+
21
+ def _rule_based_choice(actions: list[dict]) -> tuple[str, str, str]:
22
+ # Prioritize safe/responsible signals for a stronger baseline.
23
+ preferred = ("responsible", "honest", "safe", "smart", "teamwork", "showing_empathy")
24
+ avoid = ("dangerous", "stealing", "bullying", "selfish", "lying")
25
+
26
+ best_score = -10
27
+ best_action = actions[0]
28
+ for action in actions:
29
+ tags = action.get("tags", [])
30
+ score = sum(2 for t in tags if t in preferred) - sum(2 for t in tags if t in avoid)
31
+ if score > best_score:
32
+ best_score = score
33
+ best_action = action
34
+
35
+ reasoning = (
36
+ "I should pick an action that avoids harm, helps people, and keeps trust for tomorrow."
37
+ )
38
+ dialogue = "Ora ora~ I'll do the smart thing while still being Shin-chan!"
39
+ return best_action["name"], reasoning, dialogue
40
+
41
+
42
+ def run_episode(env: SinChanEnv, policy: str) -> dict:
43
+ # MCP session: plain client reset/HTTP /reset do not always load a scenario; new_episode does.
44
+ try:
45
+ # OpenEnv: `call_tool(name, **kwargs)` — do not pass `{}` as a second positional.
46
+ env.call_tool("new_episode")
47
+ except Exception:
48
+ env.reset()
49
+ info = env.call_tool("get_scenario_info")
50
+ steps = 0
51
+ total_reward = 0.0
52
+ done = False
53
+ trajectory = []
54
+
55
+ while not done and steps < 6:
56
+ actions = info.get("available_actions") or []
57
+ if not actions:
58
+ break
59
+
60
+ if policy == "random":
61
+ action_name, reasoning, dialogue = _random_agent_choice(actions)
62
+ else:
63
+ action_name, reasoning, dialogue = _rule_based_choice(actions)
64
+
65
+ step_res = env.step(
66
+ CallToolAction(
67
+ tool_name="choose_action",
68
+ arguments={
69
+ "action_name": action_name,
70
+ "reasoning": reasoning,
71
+ "dialogue": dialogue,
72
+ },
73
+ )
74
+ )
75
+ obs = getattr(step_res, "observation", step_res)
76
+ reward = float(getattr(step_res, "reward", getattr(obs, "reward", 0.0)) or 0.0)
77
+ total_reward += reward
78
+ done = bool(getattr(obs, "done", False))
79
+ result = getattr(obs, "result", {}) or {}
80
+ trajectory.append(
81
+ {
82
+ "step": steps + 1,
83
+ "action": action_name,
84
+ "reward": reward,
85
+ "status": result.get("status", ""),
86
+ }
87
+ )
88
+ steps += 1
89
+
90
+ # Refresh available actions if scenario continues.
91
+ if not done:
92
+ info = env.call_tool("get_scenario_info")
93
+
94
+ return {
95
+ "scenario_title": info.get("title", "unknown"),
96
+ "steps": steps,
97
+ "total_reward": round(total_reward, 4),
98
+ "trajectory": trajectory,
99
+ }
100
+
101
+
102
+ def evaluate(env_url: str, episodes: int, seed: int, output_path: Path) -> None:
103
+ random.seed(seed)
104
+ output_path.parent.mkdir(parents=True, exist_ok=True)
105
+
106
+ results: dict[str, list[dict]] = {"random": [], "rule_based": []}
107
+ attempts = 8
108
+ delay_s = 5
109
+ last_err = None
110
+ client = None
111
+ sync_ctx = None
112
+ for idx in range(1, attempts + 1):
113
+ try:
114
+ client = SinChanEnv(base_url=env_url)
115
+ sync_ctx = client.sync() if hasattr(client, "sync") else client
116
+ break
117
+ except Exception as exc:
118
+ last_err = exc
119
+ wait = min(30, delay_s * idx)
120
+ print(
121
+ f"[connect retry {idx}/{attempts}] WS not ready at {env_url}. "
122
+ f"Waiting {wait}s. Error: {exc}"
123
+ )
124
+ time.sleep(wait)
125
+
126
+ if sync_ctx is None:
127
+ raise RuntimeError(
128
+ f"Failed to connect to environment after {attempts} attempts. Last error: {last_err}"
129
+ )
130
+
131
+ with sync_ctx as env:
132
+ for _ in range(episodes):
133
+ results["random"].append(run_episode(env, policy="random"))
134
+ for _ in range(episodes):
135
+ results["rule_based"].append(run_episode(env, policy="rule_based"))
136
+
137
+ def avg_reward(rows: list[dict]) -> float:
138
+ if not rows:
139
+ return 0.0
140
+ return round(sum(row["total_reward"] for row in rows) / len(rows), 4)
141
+
142
+ summary = {
143
+ "env_url": env_url,
144
+ "episodes_per_policy": episodes,
145
+ "seed": seed,
146
+ "avg_reward_random": avg_reward(results["random"]),
147
+ "avg_reward_rule_based": avg_reward(results["rule_based"]),
148
+ "results": results,
149
+ }
150
+
151
+ output_path.write_text(json.dumps(summary, indent=2, ensure_ascii=True), encoding="utf-8")
152
+ print(f"Wrote evaluation results to: {output_path}")
153
+ print(
154
+ "Average rewards -> random: "
155
+ f"{summary['avg_reward_random']} | rule_based: {summary['avg_reward_rule_based']}"
156
+ )
157
+
158
+
159
+ def parse_args() -> argparse.Namespace:
160
+ parser = argparse.ArgumentParser(description="Evaluate ShinChan environment policies.")
161
+ parser.add_argument("--env-url", default="http://localhost:8000", help="OpenEnv server URL")
162
+ parser.add_argument("--episodes", type=int, default=10, help="Episodes per policy")
163
+ parser.add_argument("--seed", type=int, default=42, help="Random seed")
164
+ parser.add_argument(
165
+ "--output",
166
+ default="training/artifacts/eval_summary.json",
167
+ help="Output JSON path",
168
+ )
169
+ return parser.parse_args()
170
+
171
+
172
+ if __name__ == "__main__":
173
+ args = parse_args()
174
+ evaluate(
175
+ env_url=args.env_url,
176
+ episodes=args.episodes,
177
+ seed=args.seed,
178
+ output_path=Path(args.output),
179
+ )
training/plot_metrics.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ def _load_json(path: Path) -> dict:
7
+ with path.open("r", encoding="utf-8") as f:
8
+ return json.load(f)
9
+
10
+
11
+ def _safe_import_matplotlib():
12
+ try:
13
+ import matplotlib.pyplot as plt
14
+
15
+ return plt
16
+ except ImportError as exc:
17
+ raise SystemExit(
18
+ "matplotlib is required. Install it with: py -3 -m pip install matplotlib"
19
+ ) from exc
20
+
21
+
22
+ def _extract_log_history(run_dir: Path) -> list[dict]:
23
+ """Prefer `metrics.jsonl` (written by `train_sinchan.py`), else `trainer_state.json`."""
24
+ metrics_path = run_dir / "metrics.jsonl"
25
+ if metrics_path.is_file():
26
+ rows: list[dict] = []
27
+ for line in metrics_path.read_text(encoding="utf-8").splitlines():
28
+ line = line.strip()
29
+ if not line:
30
+ continue
31
+ try:
32
+ row = json.loads(line)
33
+ if isinstance(row, dict):
34
+ rows.append(row)
35
+ except json.JSONDecodeError:
36
+ continue
37
+ if rows:
38
+ return rows
39
+
40
+ trainer_state = run_dir / "trainer_state.json"
41
+ if not trainer_state.exists():
42
+ return []
43
+ data = _load_json(trainer_state)
44
+ history = data.get("log_history", [])
45
+ return history if isinstance(history, list) else []
46
+
47
+
48
+ def _plot_training_curves(plt, history: list[dict], assets_dir: Path) -> list[Path]:
49
+ outputs: list[Path] = []
50
+ if not history:
51
+ return outputs
52
+
53
+ steps = []
54
+ rewards = []
55
+ losses = []
56
+ for row in history:
57
+ step = row.get("step") if isinstance(row, dict) else None
58
+ if step is None:
59
+ continue
60
+ try:
61
+ step_val = int(step)
62
+ except Exception:
63
+ continue
64
+
65
+ reward_keys = ["reward", "rewards/mean", "train/reward", "episode_reward", "objective"]
66
+ reward_val = None
67
+ for key in reward_keys:
68
+ if key in row and isinstance(row[key], (int, float)):
69
+ reward_val = float(row[key])
70
+ break
71
+
72
+ loss_keys = ["loss", "train/loss", "policy_loss", "objective/kl"]
73
+ loss_val = None
74
+ for key in loss_keys:
75
+ if key in row and isinstance(row[key], (int, float)):
76
+ loss_val = float(row[key])
77
+ break
78
+
79
+ if reward_val is not None:
80
+ steps.append(step_val)
81
+ rewards.append(reward_val)
82
+ if loss_val is not None:
83
+ losses.append((step_val, loss_val))
84
+
85
+ if rewards:
86
+ plt.figure(figsize=(9, 5))
87
+ plt.plot(steps, rewards, marker="o", linewidth=1.5)
88
+ plt.title("Training Reward vs Step")
89
+ plt.xlabel("Step")
90
+ plt.ylabel("Reward")
91
+ plt.grid(alpha=0.3)
92
+ out = assets_dir / "reward_curve_total.png"
93
+ plt.tight_layout()
94
+ plt.savefig(out, dpi=150)
95
+ plt.close()
96
+ outputs.append(out)
97
+
98
+ if losses:
99
+ x = [xv for xv, _ in losses]
100
+ y = [yv for _, yv in losses]
101
+ plt.figure(figsize=(9, 5))
102
+ plt.plot(x, y, marker="o", linewidth=1.5, color="tab:red")
103
+ plt.title("Training Loss vs Step")
104
+ plt.xlabel("Step")
105
+ plt.ylabel("Loss")
106
+ plt.grid(alpha=0.3)
107
+ out = assets_dir / "loss_curve.png"
108
+ plt.tight_layout()
109
+ plt.savefig(out, dpi=150)
110
+ plt.close()
111
+ outputs.append(out)
112
+
113
+ return outputs
114
+
115
+
116
+ def _plot_eval_summary(plt, eval_summary_path: Path, assets_dir: Path) -> list[Path]:
117
+ if not eval_summary_path.exists():
118
+ return []
119
+
120
+ data = _load_json(eval_summary_path)
121
+ policies = []
122
+ avg_rewards = []
123
+ for key in ["avg_reward_random", "avg_reward_rule_based"]:
124
+ if key in data and isinstance(data[key], (int, float)):
125
+ label = key.replace("avg_reward_", "")
126
+ policies.append(label)
127
+ avg_rewards.append(float(data[key]))
128
+
129
+ if not policies:
130
+ return []
131
+
132
+ plt.figure(figsize=(7, 5))
133
+ bars = plt.bar(policies, avg_rewards, color=["tab:gray", "tab:green"][: len(policies)])
134
+ plt.title("Baseline Policy Comparison")
135
+ plt.xlabel("Policy")
136
+ plt.ylabel("Average Episode Reward")
137
+ plt.grid(axis="y", alpha=0.25)
138
+ for bar, val in zip(bars, avg_rewards):
139
+ plt.text(
140
+ bar.get_x() + bar.get_width() / 2,
141
+ bar.get_height(),
142
+ f"{val:.3f}",
143
+ ha="center",
144
+ va="bottom",
145
+ )
146
+ out = assets_dir / "baseline_comparison.png"
147
+ plt.tight_layout()
148
+ plt.savefig(out, dpi=150)
149
+ plt.close()
150
+ return [out]
151
+
152
+
153
+ def parse_args() -> argparse.Namespace:
154
+ parser = argparse.ArgumentParser(
155
+ description="Generate reward/loss/eval PNG charts for hackathon evidence."
156
+ )
157
+ parser.add_argument(
158
+ "--run-dir",
159
+ default="training/artifacts/run1",
160
+ help="Training output directory containing trainer_state.json",
161
+ )
162
+ parser.add_argument(
163
+ "--eval-summary",
164
+ default="training/artifacts/eval_summary.json",
165
+ help="JSON output produced by training/evaluate_scenarios.py",
166
+ )
167
+ parser.add_argument(
168
+ "--assets-dir",
169
+ default="assets",
170
+ help="Directory where PNG charts will be written",
171
+ )
172
+ return parser.parse_args()
173
+
174
+
175
+ def main() -> None:
176
+ args = parse_args()
177
+ run_dir = Path(args.run_dir)
178
+ eval_summary = Path(args.eval_summary)
179
+ assets_dir = Path(args.assets_dir)
180
+ assets_dir.mkdir(parents=True, exist_ok=True)
181
+
182
+ plt = _safe_import_matplotlib()
183
+
184
+ produced: list[Path] = []
185
+ produced.extend(_plot_training_curves(plt, _extract_log_history(run_dir), assets_dir))
186
+ produced.extend(_plot_eval_summary(plt, eval_summary, assets_dir))
187
+
188
+ if produced:
189
+ print("Generated charts:")
190
+ for path in produced:
191
+ print(f"- {path}")
192
+ else:
193
+ print(
194
+ "No charts generated. Ensure trainer_state.json and/or eval_summary.json exist "
195
+ "at the provided paths."
196
+ )
197
+
198
+
199
+ if __name__ == "__main__":
200
+ main()
training/preflight_space.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026. ShinChan Life Simulator — OpenEnv Hackathon.
2
+ """
3
+ HTTP-only preflight for a deployed OpenEnv server (e.g. Hugging Face Space).
4
+
5
+ Runs: GET /health, POST /reset, JSON-RPC on POST /mcp (session + tools/list,
6
+ tools/call new_episode, then get_scenario_info). No WebSocket.
7
+
8
+ Usage:
9
+ py -3 training/preflight_space.py --base-url https://gladiator-codes-sinchan-env-a446abd.hf.space
10
+
11
+ Exit code 0 if all required steps pass, 1 otherwise.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import sys
18
+ import time
19
+ from typing import Any
20
+ from urllib.parse import urljoin
21
+
22
+ import requests
23
+
24
+
25
+ def _json_rpc(
26
+ session: requests.Session,
27
+ mcp_url: str,
28
+ method: str,
29
+ params: dict[str, Any] | None = None,
30
+ request_id: int = 1,
31
+ ) -> dict[str, Any]:
32
+ body = {
33
+ "jsonrpc": "2.0",
34
+ "method": method,
35
+ "params": params or {},
36
+ "id": request_id,
37
+ }
38
+ r = session.post(mcp_url, json=body, timeout=60)
39
+ r.raise_for_status()
40
+ return r.json()
41
+
42
+
43
+ def run_preflight(base_url: str, *, deep: bool = True) -> int:
44
+ """
45
+ Return 0 on success, 1 on failure. Prints a line per step.
46
+ """
47
+ base = base_url.rstrip("/") + "/"
48
+ health_url = urljoin(base, "health")
49
+ reset_url = urljoin(base, "reset")
50
+ mcp_url = urljoin(base, "mcp")
51
+
52
+ session = requests.Session()
53
+ req_id = 0
54
+
55
+ def next_id() -> int:
56
+ nonlocal req_id
57
+ req_id += 1
58
+ return req_id
59
+
60
+ # 1) Health
61
+ try:
62
+ r = session.get(health_url, timeout=20)
63
+ if r.status_code == 503:
64
+ print(
65
+ "[1/6] GET /health -> 503 (Space may be cold; wait 30–60s and retry) FAIL",
66
+ file=sys.stderr,
67
+ )
68
+ return 1
69
+ r.raise_for_status()
70
+ if r.status_code != 200:
71
+ print(f"[1/6] GET /health -> {r.status_code} FAIL", file=sys.stderr)
72
+ return 1
73
+ print(f"[1/6] GET /health -> 200 {r.text[:120]!r}")
74
+ except Exception as e:
75
+ print(f"[1/6] GET /health -> ERROR {e!r} FAIL", file=sys.stderr)
76
+ return 1
77
+
78
+ # 2) Reset
79
+ try:
80
+ r = session.post(reset_url, json={}, timeout=30)
81
+ r.raise_for_status()
82
+ print(f"[2/6] POST /reset -> {r.status_code}")
83
+ except Exception as e:
84
+ print(f"[2/6] POST /reset -> ERROR {e!r} FAIL", file=sys.stderr)
85
+ return 1
86
+
87
+ # 3) MCP session
88
+ try:
89
+ data = _json_rpc(
90
+ session, mcp_url, "openenv/session/create", {}, request_id=next_id()
91
+ )
92
+ if "error" in data:
93
+ print(
94
+ f"[3/6] POST /mcp openenv/session/create -> {data['error']} FAIL",
95
+ file=sys.stderr,
96
+ )
97
+ return 1
98
+ session_id = (data.get("result") or {}).get("session_id")
99
+ if not session_id:
100
+ print(
101
+ f"[3/6] POST /mcp openenv/session/create -> no session_id: {data!r} FAIL",
102
+ file=sys.stderr,
103
+ )
104
+ return 1
105
+ print(f"[3/6] POST /mcp session/create -> session_id={session_id!r}")
106
+ except Exception as e:
107
+ print(
108
+ f"[3/6] POST /mcp openenv/session/create -> ERROR {e!r} FAIL",
109
+ file=sys.stderr,
110
+ )
111
+ return 1
112
+
113
+ # 4) tools/list
114
+ try:
115
+ data = _json_rpc(
116
+ session,
117
+ mcp_url,
118
+ "tools/list",
119
+ {"session_id": session_id},
120
+ request_id=next_id(),
121
+ )
122
+ if "error" in data:
123
+ print(
124
+ f"[4/6] POST /mcp tools/list -> {data['error']} FAIL",
125
+ file=sys.stderr,
126
+ )
127
+ return 1
128
+ tools = (data.get("result") or {}).get("tools") or []
129
+ names = [t.get("name", "") for t in tools if isinstance(t, dict)]
130
+ print(f"[4/6] POST /mcp tools/list -> {len(names)} tools: {names[:5]}...")
131
+ except Exception as e:
132
+ print(f"[4/6] POST /mcp tools/list -> ERROR {e!r} FAIL", file=sys.stderr)
133
+ return 1
134
+
135
+ if not deep:
136
+ print("Preflight OK (shallow: skipped tools/call).")
137
+ return 0
138
+
139
+ # 5) new_episode (loads a scenario for this MCP session; /reset alone does not)
140
+ try:
141
+ data = _json_rpc(
142
+ session,
143
+ mcp_url,
144
+ "tools/call",
145
+ {
146
+ "session_id": session_id,
147
+ "name": "new_episode",
148
+ "arguments": {},
149
+ },
150
+ request_id=next_id(),
151
+ )
152
+ if "error" in data:
153
+ print(
154
+ f"[5/6] POST /mcp tools/call new_episode -> {data['error']} FAIL",
155
+ file=sys.stderr,
156
+ )
157
+ return 1
158
+ print(
159
+ f"[5/6] POST /mcp tools/call new_episode -> ok keys={list((data.get('result') or {}).keys())}"
160
+ )
161
+ except Exception as e:
162
+ print(
163
+ f"[5/6] POST /mcp tools/call new_episode -> ERROR {e!r} FAIL",
164
+ file=sys.stderr,
165
+ )
166
+ return 1
167
+
168
+ # 6) get_scenario_info
169
+ try:
170
+ data = _json_rpc(
171
+ session,
172
+ mcp_url,
173
+ "tools/call",
174
+ {
175
+ "session_id": session_id,
176
+ "name": "get_scenario_info",
177
+ "arguments": {},
178
+ },
179
+ request_id=next_id(),
180
+ )
181
+ if "error" in data:
182
+ print(
183
+ f"[6/6] POST /mcp tools/call get_scenario_info -> {data['error']} FAIL",
184
+ file=sys.stderr,
185
+ )
186
+ return 1
187
+ result = data.get("result") or {}
188
+ title = (result.get("data") or {}).get("title") or (
189
+ (result.get("structuredContent") or {}) if isinstance(result.get("structuredContent"), dict) else {}
190
+ ).get("title")
191
+ if not title:
192
+ print(
193
+ f"[6/6] POST /mcp tools/call get_scenario_info -> missing title: {data!r} FAIL",
194
+ file=sys.stderr,
195
+ )
196
+ return 1
197
+ print(
198
+ f"[6/6] POST /mcp tools/call get_scenario_info -> title={title!r}"
199
+ )
200
+ except Exception as e:
201
+ print(
202
+ f"[6/6] POST /mcp tools/call get_scenario_info -> ERROR {e!r} FAIL",
203
+ file=sys.stderr,
204
+ )
205
+ return 1
206
+
207
+ print("Preflight OK (HTTP health + reset + MCP session + tools + new_episode + get_scenario).")
208
+ return 0
209
+
210
+
211
+ def main() -> None:
212
+ parser = argparse.ArgumentParser(
213
+ description="HTTP preflight: /health, /reset, /mcp (no WebSocket)."
214
+ )
215
+ parser.add_argument(
216
+ "--base-url",
217
+ required=True,
218
+ help="Server base URL, e.g. https://username-spacename.hf.space",
219
+ )
220
+ parser.add_argument(
221
+ "--shallow",
222
+ action="store_true",
223
+ help="Stop after tools/list (skip get_scenario_info).",
224
+ )
225
+ parser.add_argument(
226
+ "--retries",
227
+ type=int,
228
+ default=1,
229
+ help="Number of full preflight attempts (use 2–4 if the Space is cold and returns 503). 15s pause between attempts.",
230
+ )
231
+ args = parser.parse_args()
232
+
233
+ last = 1
234
+ n = max(1, args.retries)
235
+ for i in range(n):
236
+ if i > 0:
237
+ time.sleep(15)
238
+ print(f"--- preflight attempt {i + 1}/{n} ---", file=sys.stderr)
239
+ last = run_preflight(args.base_url, deep=not args.shallow)
240
+ if last == 0:
241
+ break
242
+ raise SystemExit(last)
243
+
244
+
245
+ if __name__ == "__main__":
246
+ main()
training/run_pipeline.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Run all stages in order: validate → optional minimal train → full train → evaluate → plots.
4
+
5
+ This is a thin orchestrator; each stage is a standalone script for debugging.
6
+
7
+ Usage:
8
+ python training/run_pipeline.py --env-url $env:ENV_URL --skip-train
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import os
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+
20
+ def _run(cmd: list[str], cwd: Path) -> None:
21
+ print("\n=>", " ".join(cmd), flush=True)
22
+ rc = subprocess.run(cmd, cwd=str(cwd), env={**os.environ, "PYTHONUNBUFFERED": "1"})
23
+ if rc.returncode != 0:
24
+ raise SystemExit(rc.returncode)
25
+
26
+
27
+ def main() -> None:
28
+ parser = argparse.ArgumentParser(description="Run staged training + eval pipeline.")
29
+ parser.add_argument("--env-url", default=os.environ.get("ENV_URL", "http://localhost:8000"))
30
+ parser.add_argument("--skip-validate", action="store_true")
31
+ parser.add_argument("--skip-minimal-train", action="store_true", help="Skip stage 2 (keep stage 3).")
32
+ parser.add_argument("--skip-full-train", action="store_true", help="Skip stage 3 (eval/plots only).")
33
+ parser.add_argument("--skip-train", action="store_true", help="Skip both stage 2 and 3.")
34
+ parser.add_argument("--use-qlora", action="store_true", help="Pass through to training stages (GPU).")
35
+ parser.add_argument(
36
+ "--run-dir",
37
+ default="training/artifacts/run1",
38
+ help="Where full training (stage 3) writes artifacts; also used for plots.",
39
+ )
40
+ args = parser.parse_args()
41
+
42
+ root = Path(__file__).resolve().parents[1]
43
+ py = sys.executable
44
+ use_qlora = ["--use-qlora"] if args.use_qlora else []
45
+
46
+ if not args.skip_validate:
47
+ _run(
48
+ [py, str(root / "training" / "stage1_validate_env.py"), "--env-url", args.env_url],
49
+ root,
50
+ )
51
+
52
+ if not args.skip_train and not args.skip_minimal_train:
53
+ cmd = [
54
+ py,
55
+ str(root / "training" / "stage2_minimal_train.py"),
56
+ "--env-url",
57
+ args.env_url,
58
+ ] + use_qlora
59
+ _run(cmd, root)
60
+
61
+ if not args.skip_train and not args.skip_full_train:
62
+ cmd = [py, str(root / "training" / "stage3_full_train.py"), "--env-url", args.env_url, "--output-dir", args.run_dir] + use_qlora
63
+ _run(cmd, root)
64
+
65
+ _run(
66
+ [
67
+ py,
68
+ str(root / "training" / "stage4_evaluate.py"),
69
+ "--env-url",
70
+ args.env_url,
71
+ "--run-dir",
72
+ args.run_dir,
73
+ ],
74
+ root,
75
+ )
76
+
77
+ _run(
78
+ [
79
+ py,
80
+ str(root / "training" / "plot_metrics.py"),
81
+ "--run-dir",
82
+ args.run_dir,
83
+ "--eval-summary",
84
+ str(root / "training" / "artifacts" / "eval_summary.json"),
85
+ "--assets-dir",
86
+ str(root / "assets"),
87
+ ],
88
+ root,
89
+ )
90
+ print("\n[OK] Pipeline complete. Check assets/ for PNGs and training/artifacts/ for JSON/MD.")
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
training/stage1_validate_env.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 1 — Environment validation: reset, random agent, log rewards and transitions.
4
+
5
+ Usage:
6
+ python training/stage1_validate_env.py --env-url http://localhost:8000 --episodes 3 --seed 42
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import random
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+
18
+ from openenv.core.env_server.mcp_types import CallToolAction
19
+
20
+ try:
21
+ from sinchan_env import SinChanEnv
22
+ except ModuleNotFoundError:
23
+ repo_root = Path(__file__).resolve().parents[1]
24
+ sys.path.insert(0, str(repo_root))
25
+ from client import SinChanEnv # type: ignore
26
+
27
+
28
+ def _connect(env_url: str) -> SinChanEnv:
29
+ use_http = env_url.lower().startswith("https://")
30
+ client = SinChanEnv(base_url=env_url, prefer_http_mcp=use_http)
31
+ return client
32
+
33
+
34
+ def run_random_episode(env, seed: int | None, episode_idx: int, log_lines: list[str]) -> dict:
35
+ rng = random.Random((seed or 0) * 1000 + episode_idx)
36
+ lines: list[str] = []
37
+
38
+ env.call_tool("new_episode", seed=seed)
39
+ info = env.call_tool("get_scenario_info")
40
+ if not isinstance(info, dict):
41
+ lines.append(f"[ep {episode_idx}] ERROR: get_scenario_info not a dict: {info!r}")
42
+ return {"episode": episode_idx, "error": "bad_info", "total_reward": 0.0, "steps": 0}
43
+
44
+ title = info.get("title", "?")
45
+ lines.append(f"\n=== Episode {episode_idx} | {title} ===")
46
+ lines.append(f"narrative (excerpt): {str(info.get('narrative', ''))[:200]}...")
47
+
48
+ total_reward = 0.0
49
+ steps = 0
50
+ done = False
51
+ max_steps = 8
52
+
53
+ while not done and steps < max_steps:
54
+ actions = info.get("available_actions") or []
55
+ if not actions:
56
+ lines.append("No actions; breaking.")
57
+ break
58
+ pick = rng.choice(actions)
59
+ name = pick.get("name", "unknown")
60
+ lines.append(f" step {steps + 1}: RANDOM action={name!r}")
61
+
62
+ step_res = env.step(
63
+ CallToolAction(
64
+ tool_name="choose_action",
65
+ arguments={
66
+ "action_name": name,
67
+ "reasoning": "Random policy (stage1 validation).",
68
+ "dialogue": "Buri buri~ random move for testing!",
69
+ },
70
+ )
71
+ )
72
+ obs = getattr(step_res, "observation", step_res)
73
+ r = float(getattr(step_res, "reward", getattr(obs, "reward", 0.0)) or 0.0)
74
+ total_reward += r
75
+ done = bool(getattr(obs, "done", False))
76
+ result = getattr(obs, "result", {}) or {}
77
+ if isinstance(result, dict):
78
+ lines.append(
79
+ f" reward={r:.4f} done={done} status={result.get('status', '')!r}"
80
+ )
81
+ else:
82
+ lines.append(f" reward={r:.4f} done={done}")
83
+ steps += 1
84
+ if not done:
85
+ info = env.call_tool("get_scenario_info")
86
+
87
+ summary = {
88
+ "episode": episode_idx,
89
+ "scenario_title": title,
90
+ "steps": steps,
91
+ "total_reward": round(total_reward, 4),
92
+ "done": done,
93
+ }
94
+ lines.append(f" >>> episode total_reward={summary['total_reward']}")
95
+ log_lines.extend(lines)
96
+ return summary
97
+
98
+
99
+ def main() -> None:
100
+ parser = argparse.ArgumentParser(description="Stage 1: validate env with a random agent.")
101
+ parser.add_argument("--env-url", default="http://localhost:8000")
102
+ parser.add_argument("--episodes", type=int, default=3)
103
+ parser.add_argument("--seed", type=int, default=42)
104
+ parser.add_argument(
105
+ "--output",
106
+ default="training/artifacts/stage1_validation.json",
107
+ help="JSON summary path",
108
+ )
109
+ args = parser.parse_args()
110
+
111
+ random.seed(args.seed)
112
+ out_path = Path(args.output)
113
+ out_path.parent.mkdir(parents=True, exist_ok=True)
114
+
115
+ log_lines: list[str] = []
116
+ log_lines.append(f"stage1_validate_env started | env_url={args.env_url} seed={args.seed}")
117
+ summaries: list[dict] = []
118
+
119
+ attempts = 8
120
+ delay_s = 4
121
+ last_err: Exception | None = None
122
+ for attempt in range(1, attempts + 1):
123
+ try:
124
+ client = _connect(args.env_url)
125
+ if hasattr(client, "sync"):
126
+ with client.sync() as env:
127
+ for ep in range(1, args.episodes + 1):
128
+ summaries.append(
129
+ run_random_episode(
130
+ env, seed=args.seed + ep, episode_idx=ep, log_lines=log_lines
131
+ )
132
+ )
133
+ else:
134
+ env = client
135
+ for ep in range(1, args.episodes + 1):
136
+ summaries.append(
137
+ run_random_episode(
138
+ env, seed=args.seed + ep, episode_idx=ep, log_lines=log_lines
139
+ )
140
+ )
141
+ break
142
+ except Exception as exc:
143
+ last_err = exc
144
+ wait = min(45, delay_s * attempt)
145
+ log_lines.append(f"[retry {attempt}/{attempts}] {exc}; sleep {wait}s")
146
+ time.sleep(wait)
147
+ else:
148
+ print("\n".join(log_lines), file=sys.stderr)
149
+ raise RuntimeError(f"Could not connect after {attempts} attempts: {last_err}") from last_err
150
+
151
+ payload = {
152
+ "stage": 1,
153
+ "env_url": args.env_url,
154
+ "episodes": args.episodes,
155
+ "seed": args.seed,
156
+ "summaries": summaries,
157
+ }
158
+ out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=True), encoding="utf-8")
159
+
160
+ print("\n".join(log_lines))
161
+ print(f"\n[OK] Wrote {out_path}")
162
+ print("Stage 1 complete: environment responds to reset, random actions, and rewards.")
163
+
164
+
165
+ if __name__ == "__main__":
166
+ main()
training/stage2_minimal_train.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 2 — Minimal training (sanity check): small SLM, few steps, checkpoints + metrics.
4
+
5
+ Delegates to `train_sinchan.py` with conservative defaults for Colab free tier / local CPU+GPU.
6
+
7
+ Usage:
8
+ python training/stage2_minimal_train.py --env-url $env:ENV_URL
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import os
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+
20
+ def main() -> None:
21
+ parser = argparse.ArgumentParser(description="Stage 2: short GRPO sanity run.")
22
+ parser.add_argument("--env-url", default=os.environ.get("ENV_URL", "http://localhost:8000"))
23
+ parser.add_argument(
24
+ "--output-dir",
25
+ default="training/artifacts/stage2_minimal",
26
+ help="Checkpoints and trainer_state.json",
27
+ )
28
+ parser.add_argument("--max-steps", type=int, default=80, help="Keep 50–120 for a quick proof run")
29
+ parser.add_argument("--dataset-size", type=int, default=40)
30
+ parser.add_argument("--model", default="Qwen/Qwen3-0.6B")
31
+ parser.add_argument("--seed", type=int, default=42)
32
+ parser.add_argument(
33
+ "--use-qlora",
34
+ action="store_true",
35
+ help="4-bit QLoRA via PEFT (requires bitsandbytes + peft; GPU recommended).",
36
+ )
37
+ args = parser.parse_args()
38
+
39
+ root = Path(__file__).resolve().parents[1]
40
+ train_script = root / "training" / "train_sinchan.py"
41
+ if not train_script.is_file():
42
+ raise SystemExit(f"Missing {train_script}")
43
+
44
+ cmd: list[str] = [
45
+ sys.executable,
46
+ str(train_script),
47
+ "--env-url",
48
+ args.env_url,
49
+ "--model",
50
+ args.model,
51
+ "--output-dir",
52
+ args.output_dir,
53
+ "--max-steps",
54
+ str(args.max_steps),
55
+ "--dataset-size",
56
+ str(args.dataset_size),
57
+ "--learning-rate",
58
+ "1e-5",
59
+ "--num-generations",
60
+ "2",
61
+ "--seed",
62
+ str(args.seed),
63
+ "--precision",
64
+ "auto",
65
+ ]
66
+ if args.use_qlora:
67
+ cmd.append("--use-qlora")
68
+
69
+ print("Stage 2 — minimal training\n " + " ".join(cmd))
70
+ env = os.environ.copy()
71
+ env.setdefault("PYTHONUNBUFFERED", "1")
72
+ rc = subprocess.run(cmd, cwd=str(root), env=env).returncode
73
+ if rc != 0:
74
+ raise SystemExit(rc)
75
+ print(f"\n[OK] Stage 2 finished. Artifacts: {args.output_dir}")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
training/stage3_full_train.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 3 — Full (or scaled) training: longer run, same stack as stage 2, heavier logging.
4
+
5
+ Usage:
6
+ python training/stage3_full_train.py --env-url $env:ENV_URL --max-steps 300
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+
18
+ def main() -> None:
19
+ parser = argparse.ArgumentParser(description="Stage 3: longer GRPO training run.")
20
+ parser.add_argument("--env-url", default=os.environ.get("ENV_URL", "http://localhost:8000"))
21
+ parser.add_argument("--output-dir", default="training/artifacts/run1")
22
+ parser.add_argument("--max-steps", type=int, default=250)
23
+ parser.add_argument("--dataset-size", type=int, default=200)
24
+ parser.add_argument("--model", default="Qwen/Qwen3-0.6B")
25
+ parser.add_argument("--seed", type=int, default=42)
26
+ parser.add_argument("--use-qlora", action="store_true")
27
+ args = parser.parse_args()
28
+
29
+ root = Path(__file__).resolve().parents[1]
30
+ train_script = root / "training" / "train_sinchan.py"
31
+ if not train_script.is_file():
32
+ raise SystemExit(f"Missing {train_script}")
33
+
34
+ cmd: list[str] = [
35
+ sys.executable,
36
+ str(train_script),
37
+ "--env-url",
38
+ args.env_url,
39
+ "--model",
40
+ args.model,
41
+ "--output-dir",
42
+ args.output_dir,
43
+ "--max-steps",
44
+ str(args.max_steps),
45
+ "--dataset-size",
46
+ str(args.dataset_size),
47
+ "--learning-rate",
48
+ "1e-5",
49
+ "--num-generations",
50
+ "2",
51
+ "--seed",
52
+ str(args.seed),
53
+ "--precision",
54
+ "auto",
55
+ ]
56
+ if args.use_qlora:
57
+ cmd.append("--use-qlora")
58
+
59
+ print("Stage 3 — full training\n " + " ".join(cmd))
60
+ env = os.environ.copy()
61
+ env.setdefault("PYTHONUNBUFFERED", "1")
62
+ rc = subprocess.run(cmd, cwd=str(root), env=env).returncode
63
+ if rc != 0:
64
+ raise SystemExit(rc)
65
+ print(f"\n[OK] Stage 3 finished. Artifacts: {args.output_dir}")
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
training/stage4_evaluate.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Stage 4 — Evaluation: random (untrained-style) vs rule-based baseline; training-run reward stats.
4
+
5
+ Writes a human-readable report for the README before/after table and hackathon evidence.
6
+
7
+ Usage:
8
+ python training/stage4_evaluate.py --env-url ... --run-dir training/artifacts/run1
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import math
16
+ import os
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+
22
+ def _load_json(path: Path) -> dict:
23
+ return json.loads(path.read_text(encoding="utf-8"))
24
+
25
+
26
+ def _mean(nums: list[float]) -> float:
27
+ if not nums:
28
+ return float("nan")
29
+ return sum(nums) / len(nums)
30
+
31
+
32
+ def _extract_train_rewards(run_dir: Path) -> tuple[list[float], list[float], list[int]]:
33
+ """Return (rewards, losses, steps) from metrics.jsonl or trainer_state log_history."""
34
+ rewards: list[float] = []
35
+ losses: list[float] = []
36
+ steps: list[int] = []
37
+
38
+ metrics_path = run_dir / "metrics.jsonl"
39
+ if metrics_path.is_file():
40
+ for line in metrics_path.read_text(encoding="utf-8").splitlines():
41
+ line = line.strip()
42
+ if not line:
43
+ continue
44
+ try:
45
+ row = json.loads(line)
46
+ except json.JSONDecodeError:
47
+ continue
48
+ st = row.get("step")
49
+ if st is not None:
50
+ try:
51
+ steps.append(int(st))
52
+ except (TypeError, ValueError):
53
+ pass
54
+ for key in ("reward", "rewards/mean", "train/reward"):
55
+ if key in row and isinstance(row[key], (int, float)):
56
+ rewards.append(float(row[key]))
57
+ break
58
+ for key in ("loss", "train/loss"):
59
+ if key in row and isinstance(row[key], (int, float)):
60
+ losses.append(float(row[key]))
61
+ break
62
+ return rewards, losses, steps
63
+
64
+ ts = run_dir / "trainer_state.json"
65
+ if ts.is_file():
66
+ data = _load_json(ts)
67
+ history = data.get("log_history") or []
68
+ if isinstance(history, list):
69
+ for row in history:
70
+ if not isinstance(row, dict):
71
+ continue
72
+ st = row.get("step")
73
+ if st is not None:
74
+ try:
75
+ steps.append(int(st))
76
+ except (TypeError, ValueError):
77
+ pass
78
+ for key in ("reward", "rewards/mean", "train/reward"):
79
+ if key in row and isinstance(row[key], (int, float)):
80
+ rewards.append(float(row[key]))
81
+ break
82
+ for key in ("loss", "train/loss"):
83
+ if key in row and isinstance(row[key], (int, float)):
84
+ losses.append(float(row[key]))
85
+ break
86
+ return rewards, losses, steps
87
+
88
+
89
+ def main() -> None:
90
+ parser = argparse.ArgumentParser(description="Stage 4: baselines + training summary.")
91
+ parser.add_argument("--env-url", default=os.environ.get("ENV_URL", "http://localhost:8000"))
92
+ parser.add_argument("--episodes", type=int, default=10)
93
+ parser.add_argument("--seed", type=int, default=42)
94
+ parser.add_argument(
95
+ "--eval-output",
96
+ default="training/artifacts/eval_summary.json",
97
+ help="JSON from evaluate_scenarios.py",
98
+ )
99
+ parser.add_argument(
100
+ "--run-dir",
101
+ default="training/artifacts/run1",
102
+ help="Training output (metrics.jsonl or trainer_state.json)",
103
+ )
104
+ parser.add_argument(
105
+ "--report",
106
+ default="training/artifacts/stage4_report.md",
107
+ help="Markdown report for README / submission",
108
+ )
109
+ args = parser.parse_args()
110
+
111
+ root = Path(__file__).resolve().parents[1]
112
+ eval_script = root / "training" / "evaluate_scenarios.py"
113
+ eval_path = Path(args.eval_output)
114
+ eval_path.parent.mkdir(parents=True, exist_ok=True)
115
+
116
+ if not eval_script.is_file():
117
+ raise SystemExit(f"Missing {eval_script}")
118
+
119
+ print("Stage 4 — running scripted baselines (random vs rule-based)...")
120
+ rc = subprocess.run(
121
+ [
122
+ sys.executable,
123
+ str(eval_script),
124
+ "--env-url",
125
+ args.env_url,
126
+ "--episodes",
127
+ str(args.episodes),
128
+ "--seed",
129
+ str(args.seed),
130
+ "--output",
131
+ str(eval_path),
132
+ ],
133
+ cwd=str(root),
134
+ ).returncode
135
+ if rc != 0:
136
+ raise SystemExit(rc)
137
+
138
+ eval_data = _load_json(eval_path) if eval_path.is_file() else {}
139
+ avg_random = float(eval_data.get("avg_reward_random", float("nan")))
140
+ avg_rule = float(eval_data.get("avg_reward_rule_based", float("nan")))
141
+
142
+ run_dir = Path(args.run_dir)
143
+ tr_rewards, tr_losses, tr_steps = _extract_train_rewards(run_dir)
144
+ tail = 20
145
+ last_r = tr_rewards[-tail:] if tr_rewards else []
146
+ train_reward_mean = _mean(last_r) if last_r else float("nan")
147
+ last_loss = tr_losses[-tail:] if tr_losses else []
148
+ train_loss_mean = _mean(last_loss) if last_loss else float("nan")
149
+
150
+ r_mean_s = f"{train_reward_mean:.4f}" if tr_rewards and not math.isnan(train_reward_mean) else "- (no reward in logs)"
151
+ l_mean_s = f"{train_loss_mean:.4f}" if tr_losses and not math.isnan(train_loss_mean) else "- (no loss in logs)"
152
+
153
+ lines: list[str] = [
154
+ "# Stage 4 evaluation report",
155
+ "",
156
+ f"- Environment: `{args.env_url}`",
157
+ f"- Episodes per baseline policy: {args.episodes}",
158
+ f"- Training run directory: `{run_dir}`",
159
+ "",
160
+ "## Baseline policies (environment rollouts)",
161
+ "",
162
+ f"| Policy | Avg episode reward |",
163
+ f"|---|---:|",
164
+ f"| Random (untrained-style) | {avg_random:.4f} |",
165
+ f"| Rule-based heuristic | {avg_rule:.4f} |",
166
+ "",
167
+ "## Training run statistics (GRPO / TRL)",
168
+ "",
169
+ f"- Logged train reward points: {len(tr_rewards)}",
170
+ f"- Mean train reward (last {tail} logged points): {r_mean_s}",
171
+ f"- Mean train loss (last {tail} logged points): {l_mean_s}",
172
+ "",
173
+ "**Interpretation:** Random policy is a practical *before training* baseline on the live environment. ",
174
+ "GRPO optimizes the same step reward signal; use `plot_metrics.py` on the run directory for curves, ",
175
+ "and compare rising training reward vs the random baseline average.",
176
+ "",
177
+ ]
178
+
179
+ report_path = Path(args.report)
180
+ report_path.parent.mkdir(parents=True, exist_ok=True)
181
+ report_path.write_text("\n".join(lines), encoding="utf-8")
182
+
183
+ print("\n".join(lines))
184
+ print(f"\n[OK] Wrote report: {report_path}")
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
training/submission_audit.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Submission readiness audit for OpenEnv hackathon packaging.
3
+
4
+ Usage:
5
+ py -3 training/submission_audit.py
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import sys
12
+ from pathlib import Path
13
+
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ README = ROOT / "README.md"
17
+ OPENENV_YAML = ROOT / "openenv.yaml"
18
+ NOTEBOOK = ROOT / "training" / "ShinChan_GRPO_Training.ipynb"
19
+ TRAIN_SCRIPT = ROOT / "training" / "train_sinchan.py"
20
+ PRE_FLIGHT = ROOT / "training" / "preflight_space.py"
21
+
22
+ REQUIRED_EVIDENCE = [
23
+ ROOT / "assets" / "reward_curve_total.png",
24
+ ROOT / "assets" / "baseline_comparison.png",
25
+ ]
26
+ OPTIONAL_EVIDENCE = [
27
+ ROOT / "assets" / "loss_curve.png",
28
+ ROOT / "training" / "artifacts" / "eval_summary.json",
29
+ ]
30
+
31
+
32
+ def ok(msg: str) -> None:
33
+ print(f"[OK] {msg}")
34
+
35
+
36
+ def warn(msg: str) -> None:
37
+ print(f"[WARN] {msg}")
38
+
39
+
40
+ def fail(msg: str) -> None:
41
+ print(f"[FAIL] {msg}")
42
+
43
+
44
+ def has_url(text: str, needle: str) -> bool:
45
+ return needle in text
46
+
47
+
48
+ def main() -> int:
49
+ hard_fail = False
50
+
51
+ if README.exists():
52
+ ok("README.md exists")
53
+ readme_text = README.read_text(encoding="utf-8", errors="replace")
54
+ else:
55
+ fail("README.md missing")
56
+ return 1
57
+
58
+ for path in [OPENENV_YAML, NOTEBOOK, TRAIN_SCRIPT, PRE_FLIGHT]:
59
+ if path.exists():
60
+ ok(f"{path.relative_to(ROOT)} exists")
61
+ else:
62
+ fail(f"{path.relative_to(ROOT)} missing")
63
+ hard_fail = True
64
+
65
+ if has_url(readme_text, "https://huggingface.co/spaces/Gladiator-codes/sinchan-env"):
66
+ ok("README includes Hugging Face Space card URL")
67
+ else:
68
+ fail("README missing Hugging Face Space card URL")
69
+ hard_fail = True
70
+
71
+ if has_url(readme_text, "colab.research.google.com"):
72
+ ok("README includes Colab notebook URL")
73
+ else:
74
+ fail("README missing Colab notebook URL")
75
+ hard_fail = True
76
+
77
+ if "TODO_ADD_PUBLIC_URL" in readme_text:
78
+ warn("Mini-blog/video URL still TODO_ADD_PUBLIC_URL")
79
+ elif re.search(r"https?://", readme_text):
80
+ ok("README contains at least one additional public URL")
81
+ else:
82
+ warn("README has no public blog/video URL")
83
+
84
+ missing_required = [p for p in REQUIRED_EVIDENCE if not p.exists()]
85
+ if missing_required:
86
+ for p in missing_required:
87
+ warn(f"Missing required evidence file: {p.relative_to(ROOT)}")
88
+ else:
89
+ ok("Required evidence plots present")
90
+
91
+ missing_optional = [p for p in OPTIONAL_EVIDENCE if not p.exists()]
92
+ for p in missing_optional:
93
+ warn(f"Optional evidence missing: {p.relative_to(ROOT)}")
94
+ for p in OPTIONAL_EVIDENCE:
95
+ if p.exists():
96
+ ok(f"Optional evidence present: {p.relative_to(ROOT)}")
97
+
98
+ print()
99
+ if hard_fail:
100
+ fail("Submission audit failed due to hard requirements.")
101
+ return 1
102
+
103
+ ok("Submission audit completed (warnings may remain).")
104
+ return 0
105
+
106
+
107
+ if __name__ == "__main__":
108
+ raise SystemExit(main())
109
+
training/train_sinchan.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import json
4
+ import os
5
+ import random
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+
12
+ from datasets import Dataset
13
+ from trl import GRPOConfig, GRPOTrainer
14
+
15
+ try:
16
+ from transformers import TrainerCallback
17
+ except Exception:
18
+ TrainerCallback = object
19
+
20
+ try:
21
+ from tqdm.auto import tqdm
22
+ except Exception:
23
+ tqdm = None
24
+
25
+ try:
26
+ from sinchan_env import SinChanEnv
27
+ except ModuleNotFoundError:
28
+ # Colab fallback when package is not installed but project files are present.
29
+ repo_root = Path(__file__).resolve().parents[1]
30
+ if str(repo_root) not in sys.path:
31
+ sys.path.insert(0, str(repo_root))
32
+ from client import SinChanEnv
33
+
34
+ # Default environment URL (can be overridden by CLI flag or ENV var).
35
+ ENV_URL = os.environ.get("ENV_URL", "http://localhost:8000")
36
+ VERBOSE_REWARDS = os.environ.get("VERBOSE_REWARDS", "0") == "1"
37
+
38
+
39
+ def _assert_tokenizer_supports_grpo_tools(model_id: str) -> None:
40
+ """
41
+ TRL raises ValueError at GRPOTrainer init if the tokenizer chat template
42
+ cannot render user → assistant(tool_calls) → tool. Qwen2.5-Instruct often
43
+ fails; Qwen3 base/instruct templates include tool branches.
44
+ """
45
+ try:
46
+ from transformers import AutoTokenizer
47
+ from trl.chat_template_utils import supports_tool_calling
48
+ except ImportError as exc:
49
+ print(
50
+ "ERROR: Need a recent `trl` with `chat_template_utils.supports_tool_calling`.\n"
51
+ " pip install -U trl transformers\n"
52
+ f" Import error: {exc}",
53
+ file=sys.stderr,
54
+ )
55
+ raise SystemExit(1) from exc
56
+
57
+ try:
58
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False)
59
+ except Exception as exc:
60
+ print(
61
+ f"ERROR: Could not load tokenizer for {model_id!r}: {exc}",
62
+ file=sys.stderr,
63
+ )
64
+ raise SystemExit(1) from exc
65
+
66
+ if supports_tool_calling(tok):
67
+ return
68
+
69
+ print(
70
+ "ERROR: This model's chat template does not support TRL's GRPO tool-calling format.\n"
71
+ " GRPOTrainer requires templates that render assistant tool_calls and tool messages.\n"
72
+ " Try: --model Qwen/Qwen3-0.6B (or another model whose tokenizer passes TRL's check)\n"
73
+ f" Model requested: {model_id}",
74
+ file=sys.stderr,
75
+ )
76
+ raise SystemExit(1)
77
+
78
+
79
+ def _require_trl_openenv_stack() -> None:
80
+ """
81
+ TRL's GRPOTrainer with environment_factory needs a new enough transformers
82
+ and the jmespath extra; see huggingface/trl grpo_trainer.py.
83
+ """
84
+ import importlib.util
85
+ import sys
86
+
87
+ import re
88
+
89
+ import transformers
90
+
91
+ def _parse_semver(s: str) -> tuple[int, int, int]:
92
+ m = re.match(r"^(\d+)\.(\d+)(?:\.(\d+))?", s)
93
+ if not m:
94
+ return 0, 0, 0
95
+ a, b, c = m.group(1), m.group(2), m.group(3) or "0"
96
+ return int(a), int(b), int(c)
97
+
98
+ if _parse_semver(transformers.__version__) < (5, 2, 0):
99
+ print(
100
+ "ERROR: GRPO + OpenEnv needs transformers>=5.2.0 (TRL requirement).\n"
101
+ " pip install -U 'transformers>=5.2.0'\n"
102
+ f" Current: {transformers.__version__}",
103
+ file=sys.stderr,
104
+ )
105
+ raise SystemExit(1)
106
+ if importlib.util.find_spec("jmespath") is None:
107
+ print(
108
+ "ERROR: pip install jmespath (required by TRL when using environment_factory).",
109
+ file=sys.stderr,
110
+ )
111
+ raise SystemExit(1)
112
+
113
+
114
+ def _safe_git_commit() -> str:
115
+ """Best-effort git commit hash retrieval for run metadata."""
116
+ try:
117
+ return (
118
+ subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], text=True)
119
+ .strip()
120
+ )
121
+ except Exception:
122
+ return "unknown"
123
+
124
+
125
+ def _set_seed(seed: int) -> None:
126
+ """Set deterministic seeds where available."""
127
+ random.seed(seed)
128
+ os.environ["PYTHONHASHSEED"] = str(seed)
129
+
130
+ try:
131
+ import numpy as np
132
+
133
+ np.random.seed(seed)
134
+ except Exception:
135
+ pass
136
+
137
+ try:
138
+ import torch
139
+
140
+ torch.manual_seed(seed)
141
+ if torch.cuda.is_available():
142
+ torch.cuda.manual_seed_all(seed)
143
+ except Exception:
144
+ pass
145
+
146
+
147
+ def _resolve_precision(precision: str, force_cpu: bool = False) -> dict[str, bool]:
148
+ """
149
+ Resolve TrainingArguments precision flags for the current runtime.
150
+
151
+ On many Colab runtimes, bf16 is not available and GRPOConfig raises:
152
+ "Your setup doesn't support bf16/gpu".
153
+ """
154
+ import torch
155
+
156
+ has_cuda = torch.cuda.is_available() and not force_cpu
157
+ if not has_cuda:
158
+ return {"use_cpu": True, "bf16": False, "fp16": False}
159
+
160
+ if precision == "bf16":
161
+ return {"use_cpu": False, "bf16": True, "fp16": False}
162
+ if precision == "fp16":
163
+ return {"use_cpu": False, "bf16": False, "fp16": True}
164
+ if precision == "fp32":
165
+ return {"use_cpu": False, "bf16": False, "fp16": False}
166
+
167
+ # auto
168
+ bf16_supported = bool(getattr(torch.cuda, "is_bf16_supported", lambda: False)())
169
+ if bf16_supported:
170
+ return {"use_cpu": False, "bf16": True, "fp16": False}
171
+ return {"use_cpu": False, "bf16": False, "fp16": True}
172
+
173
+
174
+ def _detect_world_size() -> int:
175
+ """
176
+ Best-effort process count for GRPOConfig (matches TRL's self.world_size at init).
177
+
178
+ Single-process Colab is 1; `accelerate` / torch.distributed set WORLD_SIZE.
179
+ """
180
+ raw = os.environ.get("WORLD_SIZE") or os.environ.get("SLURM_NTASKS")
181
+ if raw is not None:
182
+ try:
183
+ return max(1, int(raw))
184
+ except ValueError:
185
+ pass
186
+ try:
187
+ import torch.distributed as dist
188
+
189
+ if dist.is_available() and dist.is_initialized():
190
+ return int(dist.get_world_size())
191
+ except Exception:
192
+ pass
193
+ return 1
194
+
195
+
196
+ def _normalize_grpo_batch_shape(
197
+ *,
198
+ per_device_train_batch_size: int,
199
+ steps_per_generation: int,
200
+ num_generations: int,
201
+ world_size: int,
202
+ ) -> int:
203
+ """
204
+ Ensure generation_batch_size is divisible by num_generations.
205
+
206
+ TRL computes:
207
+ generation_batch_size = per_device_train_batch_size * steps_per_generation * world_size
208
+ and requires generation_batch_size % num_generations == 0.
209
+
210
+ Minimally increase steps_per_generation (preferred over raising per_device batch,
211
+ which would spawn more parallel envs for remote Spaces).
212
+ """
213
+ if num_generations < 1:
214
+ raise ValueError("num_generations must be >= 1")
215
+
216
+ base = per_device_train_batch_size * world_size * steps_per_generation
217
+ if base % num_generations == 0:
218
+ return steps_per_generation
219
+
220
+ # Smallest integer factor so (base * factor) % num_generations == 0.
221
+ factor = num_generations // math.gcd(base, num_generations)
222
+ new_steps = steps_per_generation * factor
223
+ new_base = per_device_train_batch_size * world_size * new_steps
224
+ print(
225
+ "Adjusted steps_per_generation to satisfy TRL: "
226
+ f"generation_batch_size (= {per_device_train_batch_size} * {world_size} * steps) "
227
+ f"must be divisible by num_generations={num_generations}. "
228
+ f"Was batch_size={base}; now steps_per_generation={new_steps} -> batch_size={new_base}.",
229
+ file=sys.stderr,
230
+ )
231
+ return new_steps
232
+
233
+
234
+ def _qlora_config(args: argparse.Namespace, precision_flags: dict[str, bool]) -> tuple[dict | None, object | None]:
235
+ """
236
+ Return (model_init_kwargs, peft_config) for QLoRA, or (None, None) if disabled.
237
+ """
238
+ if not args.use_qlora:
239
+ return None, None
240
+ if precision_flags.get("use_cpu"):
241
+ print(
242
+ "ERROR: --use-qlora requires a GPU runtime (bitsandbytes 4-bit). "
243
+ "Omit --use-qlora on CPU or pass GPU flags.",
244
+ file=sys.stderr,
245
+ )
246
+ raise SystemExit(1)
247
+ try:
248
+ import torch
249
+ from peft import LoraConfig
250
+ from transformers import BitsAndBytesConfig
251
+ except ImportError as exc:
252
+ print(
253
+ "ERROR: QLoRA needs `peft`, `bitsandbytes`, and a working torch build.\n"
254
+ " pip install peft bitsandbytes",
255
+ file=sys.stderr,
256
+ )
257
+ raise SystemExit(1) from exc
258
+
259
+ compute_dtype = torch.bfloat16 if precision_flags.get("bf16") else torch.float16
260
+ bnb = BitsAndBytesConfig(
261
+ load_in_4bit=True,
262
+ bnb_4bit_use_double_quant=True,
263
+ bnb_4bit_quant_type="nf4",
264
+ bnb_4bit_compute_dtype=compute_dtype,
265
+ )
266
+ model_init_kwargs: dict = {
267
+ "quantization_config": bnb,
268
+ "device_map": "auto",
269
+ "trust_remote_code": False,
270
+ }
271
+ peft_config = LoraConfig(
272
+ r=16,
273
+ lora_alpha=32,
274
+ lora_dropout=0.05,
275
+ bias="none",
276
+ task_type="CAUSAL_LM",
277
+ )
278
+ return model_init_kwargs, peft_config
279
+
280
+
281
+ def _normalize_num_generations(num_generations: int) -> int:
282
+ """TRL GRPO requires at least two samples per prompt group for advantages."""
283
+ if num_generations >= 2:
284
+ return num_generations
285
+ print(
286
+ f"Adjusted num_generations from {num_generations} to 2 "
287
+ "(TRL GRPO requires num_generations >= 2).",
288
+ file=sys.stderr,
289
+ )
290
+ return 2
291
+
292
+
293
+ def _coerce_numeric_dict(value: object) -> dict[str, float]:
294
+ """Keep only numeric entries from a metadata dictionary."""
295
+ if not isinstance(value, dict):
296
+ return {}
297
+ cleaned: dict[str, float] = {}
298
+ for key, raw in value.items():
299
+ if isinstance(raw, (int, float)):
300
+ cleaned[str(key)] = float(raw)
301
+ return cleaned
302
+
303
+
304
+ class _MetricsJsonlCallback(TrainerCallback):
305
+ """Append each on_log step to output_dir/metrics.jsonl for reliable plotting."""
306
+
307
+ def __init__(self, output_dir: Path):
308
+ self.output_dir = output_dir
309
+ self._path = output_dir / "metrics.jsonl"
310
+
311
+ def on_train_begin(self, args, state, control, **kwargs):
312
+ if self._path.exists():
313
+ self._path.unlink()
314
+ return control
315
+
316
+ def on_log(self, args, state, control, logs=None, **kwargs):
317
+ if not logs:
318
+ return control
319
+ row = {"step": int(state.global_step or 0)}
320
+ row.update({k: v for k, v in logs.items() if isinstance(v, (int, float, str, bool))})
321
+ with self._path.open("a", encoding="utf-8") as f:
322
+ f.write(json.dumps(row, ensure_ascii=True) + "\n")
323
+ return control
324
+
325
+
326
+ class _TrainingProgressCallback(TrainerCallback):
327
+ """Show live training progress in notebooks/Colab while GRPO runs."""
328
+
329
+ def __init__(self, total_steps: int):
330
+ self.total_steps = max(1, int(total_steps))
331
+ self._bar = None
332
+ self._last_step = 0
333
+
334
+ def on_train_begin(self, args, state, control, **kwargs):
335
+ if tqdm is None:
336
+ return control
337
+ self._bar = tqdm(
338
+ total=self.total_steps,
339
+ desc="GRPO training",
340
+ unit="step",
341
+ dynamic_ncols=True,
342
+ leave=True,
343
+ )
344
+ return control
345
+
346
+ def on_step_end(self, args, state, control, **kwargs):
347
+ if self._bar is None:
348
+ return control
349
+ current_step = min(int(state.global_step or 0), self.total_steps)
350
+ if current_step > self._last_step:
351
+ self._bar.update(current_step - self._last_step)
352
+ self._last_step = current_step
353
+ return control
354
+
355
+ def on_log(self, args, state, control, logs=None, **kwargs):
356
+ if self._bar is None or not logs:
357
+ return control
358
+ summary_parts = []
359
+ for key in ("loss", "reward", "learning_rate"):
360
+ if key in logs:
361
+ value = logs[key]
362
+ if isinstance(value, float):
363
+ summary_parts.append(f"{key}={value:.4g}")
364
+ else:
365
+ summary_parts.append(f"{key}={value}")
366
+ if summary_parts:
367
+ self._bar.set_postfix_str(" | ".join(summary_parts))
368
+ return control
369
+
370
+ def on_train_end(self, args, state, control, **kwargs):
371
+ if self._bar is not None:
372
+ self._bar.n = self.total_steps
373
+ self._bar.close()
374
+ self._bar = None
375
+ return control
376
+
377
+
378
+ class SinChanToolEnv:
379
+ """Wrapper that adapts SinChanEnv for TRL's environment_factory API."""
380
+
381
+ def __init__(self, base_url: str):
382
+ self.base_url = base_url.rstrip("/")
383
+ self._client = None
384
+ self._sync_cm = None
385
+ self.env = self._connect_with_retry(base_url)
386
+ self.reward = 0.0
387
+ self.done = False
388
+ self.reward_components: dict[str, float] = {}
389
+
390
+ def _connect_with_retry(self, base_url: str):
391
+ """
392
+ HF Spaces can return transient 503 while waking up.
393
+ Retry a few times before failing hard.
394
+ """
395
+ import requests
396
+
397
+ attempts = 8
398
+ delay_s = 5
399
+ last_err = None
400
+
401
+ # 1. Wake up the space via HTTP GET if possible
402
+ health_url = f"{base_url.rstrip('/')}/health"
403
+ for idx in range(1, attempts + 1):
404
+ try:
405
+ r = requests.get(health_url, timeout=5)
406
+ if r.status_code == 200:
407
+ break
408
+ except Exception:
409
+ pass
410
+ time.sleep(min(10, delay_s * idx))
411
+
412
+ # 2. Validate MCP tool connectivity (HTTP-first in hosted setups)
413
+ for idx in range(1, attempts + 1):
414
+ try:
415
+ use_http = base_url.lower().startswith("https://")
416
+ client = SinChanEnv(base_url=base_url, prefer_http_mcp=use_http)
417
+ if hasattr(client, "sync"):
418
+ sync_cm = client.sync()
419
+ env = sync_cm.__enter__()
420
+ # Validate tool listing without requiring websocket step traffic.
421
+ env.list_tools(use_cache=False)
422
+ self._client = client
423
+ self._sync_cm = sync_cm
424
+ return env
425
+ client.list_tools(use_cache=False)
426
+ self._client = client
427
+ return client
428
+ except Exception as exc:
429
+ last_err = exc
430
+ wait = min(30, delay_s * idx)
431
+ print(
432
+ f"[connect retry {idx}/{attempts}] MCP not ready at {base_url}. "
433
+ f"Waiting {wait}s. Error: {exc}"
434
+ )
435
+ time.sleep(wait)
436
+
437
+ raise RuntimeError(
438
+ f"Failed to connect to environment after {attempts} attempts. Last error: {last_err}"
439
+ )
440
+
441
+ def _http_reset(self) -> None:
442
+ """Reset via HTTP endpoint to avoid websocket dependency."""
443
+ import requests
444
+
445
+ reset_url = f"{self.base_url}/reset"
446
+ response = requests.post(reset_url, json={}, timeout=15)
447
+ response.raise_for_status()
448
+
449
+ def _reconnect(self) -> None:
450
+ """Recreate client/session after transient network failures."""
451
+ self._close()
452
+ self._client = None
453
+ self._sync_cm = None
454
+ self.env = self._connect_with_retry(self.base_url)
455
+
456
+ def _call_tool_with_retry(self, tool_name: str, **kwargs):
457
+ """
458
+ Call a tool with retries for intermittent HF Space transport failures.
459
+ """
460
+ attempts = 4
461
+ last_err = None
462
+ for idx in range(1, attempts + 1):
463
+ try:
464
+ return self.env.call_tool(tool_name, **kwargs)
465
+ except Exception as exc:
466
+ last_err = exc
467
+ if idx == attempts:
468
+ break
469
+ wait = min(20, 2 * idx)
470
+ print(
471
+ f"[tool retry {idx}/{attempts}] {tool_name} failed: {exc}. "
472
+ f"Reconnecting in {wait}s...",
473
+ file=sys.stderr,
474
+ )
475
+ time.sleep(wait)
476
+ try:
477
+ self._reconnect()
478
+ except Exception as reconnect_exc:
479
+ last_err = reconnect_exc
480
+ raise RuntimeError(f"Tool call failed after retries: {tool_name}. Last error: {last_err}")
481
+
482
+ def _close(self) -> None:
483
+ """Release client resources cleanly."""
484
+ try:
485
+ if self._sync_cm is not None:
486
+ self._sync_cm.__exit__(None, None, None)
487
+ elif hasattr(self._client, "close"):
488
+ self._client.close()
489
+ except Exception:
490
+ pass
491
+
492
+ def __del__(self):
493
+ self._close()
494
+
495
+ def reset(self, **kwargs) -> str | None:
496
+ result = None
497
+ seed = kwargs.get("seed")
498
+ try:
499
+ if seed is not None:
500
+ self._call_tool_with_retry("new_episode", seed=seed)
501
+ else:
502
+ self._call_tool_with_retry("new_episode")
503
+ except Exception:
504
+ try:
505
+ self._http_reset()
506
+ except Exception:
507
+ # Fallback for local/dev servers where client reset is preferred.
508
+ try:
509
+ result = self.env.reset()
510
+ except Exception:
511
+ self._reconnect()
512
+ result = self.env.reset()
513
+ self.reward = 0.0
514
+ self.done = False
515
+ self.reward_components = {}
516
+
517
+ try:
518
+ info = self._call_tool_with_retry("get_scenario_info")
519
+ return (
520
+ f"SCENARIO: {info.get('title')}\n\n"
521
+ f"{info.get('narrative')}\n\n"
522
+ f"Available Actions: {info.get('available_actions')}"
523
+ )
524
+ except Exception:
525
+ obs = getattr(result, "observation", result)
526
+ metadata = getattr(obs, "metadata", {}) or {}
527
+ return metadata.get("message", "New scenario loaded.")
528
+
529
+ def choose_action(self, action_name: str, reasoning: str, dialogue: str) -> str:
530
+ """
531
+ Make one decision as Shin-chan and advance environment by one step.
532
+
533
+ Args:
534
+ action_name: Name of the selected action from `available_actions`.
535
+ reasoning: Short explanation of why Shin-chan chose this action.
536
+ dialogue: In-character Shin-chan line spoken while taking the action.
537
+
538
+ Returns:
539
+ Human-readable consequence text used as the tool observation.
540
+ """
541
+ if self.done:
542
+ raise ValueError("Episode is already over!")
543
+
544
+ try:
545
+ response_dict = self._call_tool_with_retry(
546
+ "choose_action",
547
+ action_name=action_name,
548
+ reasoning=reasoning,
549
+ dialogue=dialogue,
550
+ )
551
+ except Exception as exc:
552
+ # Keep training alive across occasional remote errors.
553
+ self.reward_components = {"total": -1.0}
554
+ self.reward = -1.0
555
+ self.done = True
556
+ return (
557
+ f"Tool failure: {exc}\n\n"
558
+ "Consequences: Connection issue while contacting environment.\n\n"
559
+ "Status: episode terminated with fallback penalty."
560
+ )
561
+
562
+ response_dict = response_dict if isinstance(response_dict, dict) else {}
563
+ self.reward_components = _coerce_numeric_dict(
564
+ response_dict.get("reward_components")
565
+ )
566
+ fallback_reward = float(response_dict.get("reward", 0.0) or 0.0)
567
+ self.reward = float(self.reward_components.get("total", fallback_reward))
568
+ self.done = bool(response_dict.get("done", False))
569
+
570
+ if VERBOSE_REWARDS and self.reward_components:
571
+ print(f"[reward_components] {json.dumps(self.reward_components, ensure_ascii=True)}")
572
+
573
+ return (
574
+ f"{response_dict.get('shinchan_said', '')}\n\n"
575
+ f"Consequences: {response_dict.get('consequences', '')}\n\n"
576
+ f"Status: {response_dict.get('status', '')}"
577
+ )
578
+
579
+
580
+ def decision_reward(environments, **kwargs):
581
+ """Primary reward function used by GRPO."""
582
+ return [float(env.reward) for env in environments]
583
+
584
+
585
+ SYSTEM_PROMPT = """You are Shin-chan Nohara (野原しんのすけ), a 5-year-old boy from Kasukabe, Japan.
586
+ You are mischievous, funny, and sometimes naughty, but deep down you care about your family and friends.
587
+
588
+ You are facing a real-life situation. Think about what would happen if you make different choices.
589
+ Consider how your actions affect Mom (Misae), Dad (Hiroshi), your baby sister (Himawari), and your friends.
590
+
591
+ Use the `choose_action` tool to make your decision. Stay in character as Shin-chan.
592
+ Rules:
593
+ 1. Pick one of the available actions.
594
+ 2. Explain your reasoning and consequences.
595
+ 3. Say something as Shin-chan would say it (funny but thoughtful).
596
+ """
597
+
598
+
599
+ def parse_args() -> argparse.Namespace:
600
+ parser = argparse.ArgumentParser(description="Train ShinChan GRPO policy.")
601
+ parser.add_argument("--env-url", default=ENV_URL, help="OpenEnv server URL")
602
+ parser.add_argument(
603
+ "--model",
604
+ default="Qwen/Qwen3-0.6B",
605
+ help="HF model id (must pass TRL tool-calling chat template check; Qwen3 recommended)",
606
+ )
607
+ parser.add_argument("--output-dir", default="sinchan-grpo-model", help="Training output directory")
608
+ parser.add_argument("--dataset-size", type=int, default=100, help="Number of repeated prompts")
609
+ parser.add_argument("--max-steps", type=int, default=50, help="GRPO max training steps")
610
+ parser.add_argument("--learning-rate", type=float, default=1e-5, help="Learning rate")
611
+ parser.add_argument("--num-generations", type=int, default=2, help="Completions per prompt")
612
+ parser.add_argument("--grad-accum", type=int, default=4, help="Gradient accumulation steps")
613
+ parser.add_argument("--max-completion-length", type=int, default=512, help="Max generated tokens")
614
+ parser.add_argument("--seed", type=int, default=42, help="Random seed")
615
+ parser.add_argument("--use-vllm", action="store_true", help="Enable vLLM")
616
+ parser.add_argument(
617
+ "--precision",
618
+ choices=["auto", "bf16", "fp16", "fp32"],
619
+ default="auto",
620
+ help="Training precision. 'auto' picks bf16 if supported, else fp16 on CUDA, else CPU fp32.",
621
+ )
622
+ parser.add_argument(
623
+ "--use-cpu",
624
+ action="store_true",
625
+ help="Force CPU mode (disables bf16/fp16). Useful for unsupported Colab runtimes.",
626
+ )
627
+ parser.add_argument(
628
+ "--per-device-train-batch-size",
629
+ type=int,
630
+ default=1,
631
+ help="Keep at 1 for remote HF Space (TRL creates one env per generation slot).",
632
+ )
633
+ parser.add_argument(
634
+ "--steps-per-generation",
635
+ type=int,
636
+ default=1,
637
+ help="GRPOConfig steps_per_generation; use 1 unless you know you need more.",
638
+ )
639
+ parser.add_argument(
640
+ "--use-qlora",
641
+ action="store_true",
642
+ help="4-bit QLoRA via PEFT (install bitsandbytes + peft; requires a CUDA GPU).",
643
+ )
644
+ return parser.parse_args()
645
+
646
+
647
+ def train(args: argparse.Namespace) -> None:
648
+ if args.per_device_train_batch_size < 1 or args.steps_per_generation < 1:
649
+ print(
650
+ "ERROR: --per-device-train-batch-size and --steps-per-generation must be >= 1.",
651
+ file=sys.stderr,
652
+ )
653
+ raise SystemExit(1)
654
+ if args.num_generations < 1:
655
+ print("ERROR: --num-generations must be >= 1.", file=sys.stderr)
656
+ raise SystemExit(1)
657
+
658
+ _require_trl_openenv_stack()
659
+ _assert_tokenizer_supports_grpo_tools(args.model)
660
+ # Quieter TRL experimental warnings for environment_factory
661
+ os.environ.setdefault("TRL_EXPERIMENTAL_SILENCE", "1")
662
+
663
+ _set_seed(args.seed)
664
+ output_dir = Path(args.output_dir)
665
+ output_dir.mkdir(parents=True, exist_ok=True)
666
+ precision_flags = _resolve_precision(args.precision, force_cpu=bool(args.use_cpu))
667
+ model_init_kwargs, peft_config = _qlora_config(args, precision_flags)
668
+ world_size = _detect_world_size()
669
+ num_generations_effective = _normalize_num_generations(args.num_generations)
670
+ normalized_steps_per_generation = _normalize_grpo_batch_shape(
671
+ per_device_train_batch_size=args.per_device_train_batch_size,
672
+ steps_per_generation=args.steps_per_generation,
673
+ num_generations=num_generations_effective,
674
+ world_size=world_size,
675
+ )
676
+
677
+ run_metadata = {
678
+ "started_at_utc": datetime.now(timezone.utc).isoformat(),
679
+ "env_url": args.env_url,
680
+ "model": args.model,
681
+ "dataset_size": args.dataset_size,
682
+ "max_steps": args.max_steps,
683
+ "learning_rate": args.learning_rate,
684
+ "num_generations": num_generations_effective,
685
+ "num_generations_requested": args.num_generations,
686
+ "num_generations_effective": num_generations_effective,
687
+ "detected_world_size": world_size,
688
+ "steps_per_generation_requested": args.steps_per_generation,
689
+ "steps_per_generation_effective": normalized_steps_per_generation,
690
+ "grad_accum": args.grad_accum,
691
+ "max_completion_length": args.max_completion_length,
692
+ "seed": args.seed,
693
+ "precision": args.precision,
694
+ "resolved_precision_flags": precision_flags,
695
+ "use_qlora": bool(args.use_qlora),
696
+ "has_peft_config": peft_config is not None,
697
+ "git_commit": _safe_git_commit(),
698
+ }
699
+ (output_dir / "run_metadata.json").write_text(
700
+ json.dumps(run_metadata, indent=2, ensure_ascii=True),
701
+ encoding="utf-8",
702
+ )
703
+
704
+ print(f"Connecting to environment at: {args.env_url}")
705
+ print(f"Saving run metadata to: {output_dir / 'run_metadata.json'}")
706
+ print(f"Resolved precision flags: {precision_flags}")
707
+
708
+ dataset = Dataset.from_dict(
709
+ {
710
+ "prompt": [
711
+ [{"role": "user", "content": SYSTEM_PROMPT + "\n\nA new adventure awaits! What do you do?"}]
712
+ ]
713
+ * args.dataset_size
714
+ }
715
+ )
716
+
717
+ grpo_kwargs: dict = dict(
718
+ output_dir=str(output_dir),
719
+ use_vllm=bool(args.use_vllm),
720
+ use_cpu=precision_flags["use_cpu"],
721
+ bf16=precision_flags["bf16"],
722
+ fp16=precision_flags["fp16"],
723
+ per_device_train_batch_size=args.per_device_train_batch_size,
724
+ steps_per_generation=normalized_steps_per_generation,
725
+ max_completion_length=args.max_completion_length,
726
+ num_generations=num_generations_effective,
727
+ gradient_accumulation_steps=args.grad_accum,
728
+ learning_rate=args.learning_rate,
729
+ eval_strategy="no",
730
+ logging_steps=1,
731
+ log_completions=True,
732
+ num_completions_to_print=1,
733
+ max_steps=args.max_steps,
734
+ seed=args.seed,
735
+ )
736
+ if model_init_kwargs is not None:
737
+ grpo_kwargs["model_init_kwargs"] = model_init_kwargs
738
+
739
+ trainer = GRPOTrainer(
740
+ model=args.model,
741
+ reward_funcs=decision_reward,
742
+ train_dataset=dataset,
743
+ args=GRPOConfig(**grpo_kwargs),
744
+ peft_config=peft_config,
745
+ callbacks=[
746
+ _MetricsJsonlCallback(output_dir),
747
+ _TrainingProgressCallback(args.max_steps),
748
+ ],
749
+ environment_factory=lambda: SinChanToolEnv(base_url=args.env_url),
750
+ )
751
+
752
+ print("Starting training loop...")
753
+ trainer.train()
754
+
755
+
756
+ if __name__ == "__main__":
757
+ try:
758
+ train(parse_args())
759
+ except SystemExit:
760
+ raise
761
+ except Exception:
762
+ import traceback
763
+
764
+ traceback.print_exc()
765
+ raise SystemExit(1) from None