Hermes Bot commited on
Commit ·
9132bed
1
Parent(s): fa78a42
Co-Authored-By: Nanoboozhoo <nanoboozhoo@git-aaaki>
Files changed (9)
- .agents/tasks/TASK.2026-06-08.mdAdded+18
- projects/tinybard/.gitignoreAdded+10
- projects/tinybard/README.mdAdded+90
- projects/tinybard/__init__.pyAdded+1
- projects/tinybard/app.pyAdded+427
- projects/tinybard/requirements.txtAdded+7
- projects/tinybard/static/index.htmlAdded+65
- projects/tinybard/static/main.jsAdded+263
- projects/tinybard/static/style.cssAdded+394
123456789101112131415161718# Task: Hackathon Setup and TinyBard Start
- Branch: feat/hackathon-tinybard-setup- Date: 2026-06-08
## Chain-of-Draft
1. Initialize task file.2. Setup TinyBard scaffold.3. Create GitHub repo.4. Local testing setup.5. Upgrade apps to gr.Server.6. Deploy HF Spaces.7. Configure agents-cli.8. Update llms.txt.
####Proceeding with implementation.12345678910# AINISH Coder Tooling Distribution - Git Ignore Patterns__pycache__/*.pycvenv/.venv/.DS_Store*.logtmp/models/*.gguf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990---title: TinyBardemoji: ⚔colorFrom: greencolorTo: bluesdk: gradiosdk_version: 6.0.0app_file: app.pypinned: falselicense: apache-2.0tags: - text-adventure - interactive-fiction - llama-cpp - thousand-token-wood - build-small-hackathon - tiny-titan - llama-champion - off-brand - off-the-grid - mcp-server---
# ⚔ TinyBard — Micro Interactive Text Adventure Generator
**A ≤4B LLM generates 5-minute interactive text adventures with a retro CRT terminal UI.**
TinyBard uses gr.Server (FastAPI) with a fully custom HTML/CSS/JS frontend and MCP server mode enabled.Every adventure is procedurally generated — rooms, NPCs, items, and branching narratives on the fly.
## Features
- **Dynamic Adventures** — LLM generates unique story beats for every playthrough- **3 Genres** — Fantasy, Sci-Fi, Cyberpunk- **CRT Terminal UI** — Retro pixel-art aesthetic with scanlines and phosphor glow- **MCP Server** — Exposes `start_game` and `make_choice` as MCP tools for AI agent integration- **100% Local** — No cloud APIs. Runs on llama.cpp with GGUF quantized models- **Procedural Fallback** — Full game engine works even without the LLM model loaded
## Quick Start
```bashgit clone <this-repo>cd tinybardpip install -r requirements.txt
# Download model (Q4_K_M quant, ~1GB)huggingface-cli download mradermacher/VibeThinker-1.5B-GGUF \ --include "VibeThinker-1.5B.Q8_0.gguf" \ --local-dir ./models
# Set model pathexport TINYBARD_MODEL_PATH=./models/VibeThinker-1.5B.Q8_0.gguf
# Launchpython app.py```
## Model
| Model | Size | Purpose | License ||-------|------|---------|---------|| VibeThinker 1.5B | 1.5B | Interactive story generation | Apache 2.0 |
Fits the Tiny Titan badge (≤4B params). Runs on any laptop.
## MCP Integration
TinyBard runs with `mcp_server=True`, exposing these tools:
- **`start_game`** — Start a new adventure. Args: `genre` (fantasy/scifi/cyberpunk)- **`make_choice`** — Submit a player choice. Args: `choice`, `genre`, `step`, `health`, `history_json`
Connect from any MCP client (Claude Desktop, Cursor, etc.) to the SSE endpoint.
## Hackathon Track
**Thousand Token Wood** + **Tiny Titan** + **Llama Champion**
### Bonus Badges- **Llama Champion** — Uses llama.cpp runtime- **Tiny Titan** — Model is 1.5B (well under 4B limit)- **Off-Brand** — Fully custom gr.Server frontend (not gr.Blocks)- **Off the Grid** — Fully local, no API calls- **Field Notes** — Blog post about tiny model interactive fiction
## Credits
Built for the Build Small Hackathon 2026.The AI is load-bearing: every story, choice, and narrative arc is generated live.1"""TinyBard — Micro Interactive Text Adventure Generator."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427#!/usr/bin/env python3"""TinyBard — Micro Interactive Text Adventure Generator======================================================Custom FastAPI app with Gradio Blocks mounted for MCP tool integration.Retro CRT terminal frontend served as static HTML.
Targets: Thousand Token Wood + Tiny Titan + Llama Champion tracks.Badges: Llama Champion, Tiny Titan, Off-Brand (custom frontend), Off the Grid, Field Notes."""
import osimport jsonimport randomimport loggingfrom pathlib import Pathfrom typing import Optional, Dict, List
import gradio as grfrom fastapi import FastAPIfrom fastapi.responses import HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom gradio import mount_gradio_app
logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",)log = logging.getLogger("tinybard")
# ---------------------------------------------------------------------------# Config & Paths# ---------------------------------------------------------------------------BASE_DIR = Path(__file__).parentSTATIC_DIR = BASE_DIR / "static"
MODEL_PATH = os.environ.get( "TINYBARD_MODEL_PATH", str(Path("/Volumes/1tb-sandisk/ml-models/huggingface/models--mradermacher--VibeThinker-1.5B-GGUF/snapshots/d0d66139a78030a92a582f966b0f7cbbb3b19406/VibeThinker-1.5B.Q8_0.gguf")))
# ---------------------------------------------------------------------------# Llama.cpp Inference Setup# ---------------------------------------------------------------------------_llm = None_llm_failed = False
def get_llm(): """Lazy-load the GGUF model via llama-cpp-python.""" global _llm, _llm_failed if _llm is not None: return _llm if _llm_failed: return None
if not Path(MODEL_PATH).exists(): log.warning(f"Model file not found at {MODEL_PATH}. Fallback mode active.") _llm_failed = True return None
try: from llama_cpp import Llama log.info(f"Loading VibeThinker-1.5B from {MODEL_PATH} ...") _llm = Llama( model_path=MODEL_PATH, n_ctx=2048, n_threads=int(os.environ.get("TINYBARD_THREADS", "4")), verbose=False, ) log.info("Model loaded successfully ✓") return _llm except Exception as e: log.error(f"Failed to load LLM model: {e}") _llm_failed = True return None
# ---------------------------------------------------------------------------# Procedural Fallback Adventure Engine# ---------------------------------------------------------------------------GENRES = { "fantasy": { "start": "You stand before the gates of the Whisperwood. The ancient trees hum with a faint violet energy.", "nodes": [ { "story": "A glowing sprite appears, offering a golden key or a mossy vial.", "choices": ["Take the golden key", "Drink the mossy vial", "Ignore the sprite and press forward"] }, { "story": "You encounter a moss-covered stone golem blocking the path. It speaks in riddles.", "choices": ["Answer its riddle with a joke", "Use your golden key if you have it", "Try to climb over it"] }, { "story": "You discover a hidden pool reflecting stars that aren't in the sky.", "choices": ["Drink from the star pool", "Rest by the shore", "Toss a coin into the water"] } ], "win": "You find the heart of the forest and unlock the ancient relic. You are victorious!", "lose": "The energy of the forest overwhelms you. You fade into the whispers of the wood." }, "scifi": { "start": "The emergency lights flicker red in the derelict cargo bay of USS Horizon. Gravity is failing.", "nodes": [ { "story": "A leaking fuel pipe blocks the corridor ahead. Sparking wires fill the air.", "choices": ["Siphon the fuel", "Bypass the circuits", "Wait for the cycle to clear"] }, { "story": "An automated security drone activates, targeting you with its laser system.", "choices": ["Hack the drone terminal", "Throw scrap metal to distract it", "Run for the airlock"] }, { "story": "You reach the main computer terminal. The AI core is corrupt but online.", "choices": ["Initiate override protocol", "Ask the AI for help", "Pull the main power breaker"] } ], "win": "You restore life support and secure the escape pod. You survive!", "lose": "The hull breaches. You are swept into the cold embrace of outer space." }, "cyberpunk": { "start": "Acid rain beats against the neon signs of Sector 9. Your neural interface is glitching.", "nodes": [ { "story": "A street dealer offers to patch your wetware for a few credits or a favor.", "choices": ["Accept the shady patch", "Decline and buy a neural booster", "Threaten him for info"] }, { "story": "A corporate agent corners you in a wet alleyway. He demands your datapad.", "choices": ["Upload a virus to his cyber-eyes", "Hand over a fake datapad", "Sprint up the fire escape"] }, { "story": "You infiltrate the mainframe room of Shinra-Tech. The security grid is active.", "choices": ["Jack in directly", "Use your backup deck", "Short-circuit the access node"] } ], "win": "You upload the corporate secrets to the net. Sector 9 is free. You win!", "lose": "Your brain fried due to feedback from the security grid. Game Over." }}
def generate_procedural_step(genre: str, step: int, health: int, choice: str = "") -> dict: """Generate a fallback adventure step without LLM.""" genre_data = GENRES.get(genre.lower(), GENRES["fantasy"])
if step == 0: return { "story": genre_data["start"], "choices": genre_data["nodes"][0]["choices"], "health": health, "step": 1, "game_over": False }
health_delta = random.choice([-15, 0, 10]) new_health = max(0, min(100, health + health_delta))
if new_health <= 0: return { "story": f"After choosing: '{choice}'. " + genre_data["lose"], "choices": [], "health": 0, "step": step + 1, "game_over": True }
if step >= 4: return { "story": f"After choosing: '{choice}'. " + genre_data["win"], "choices": [], "health": new_health, "step": step + 1, "game_over": True }
node = genre_data["nodes"][step % len(genre_data["nodes"])] return { "story": f"You choose: '{choice}'.\n\n{node['story']}", "choices": node["choices"], "health": new_health, "step": step + 1, "game_over": False }
# ---------------------------------------------------------------------------# LLM Generation Logic# ---------------------------------------------------------------------------def generate_llm_story(prompt: str, max_tokens: int = 150) -> str: """Generate story text via llama.cpp.""" llm = get_llm() if not llm: return "" try: response = llm( prompt, max_tokens=max_tokens, temperature=0.7, stop=["\n\n", "User:", "Narrator:"], ) return response["choices"][0]["text"].strip() except Exception as e: log.error(f"LLM generation error: {e}") return ""
def format_prompt(genre: str, history: List[Dict[str, str]], next_instruction: str) -> str: """Build the narrative prompt for the LLM.""" prompt = ( "You are the narrator of an interactive text adventure game.\n" f"Genre: {genre}\n" "Rules:\n" "1. Write in the second person ('You...').\n" "2. Keep descriptions highly atmospheric, but short (under 3 sentences).\n" "3. Focus on action, mystery, and choice.\n\n" ) for h in history: if h["role"] == "player": prompt += f"Player choice: {h['text']}\n" else: prompt += f"Narrator: {h['text']}\n"
prompt += f"{next_instruction}\n" return prompt
# ---------------------------------------------------------------------------# Gradio Blocks — API endpoints (exposed as MCP tools)# ---------------------------------------------------------------------------def create_gradio_app() -> gr.Blocks: """Build the Gradio Blocks app with API endpoints for MCP integration."""
with gr.Blocks(title="TinyBard API") as blocks: # Hidden state — not rendered in UI, used by API genre_input = gr.Textbox(label="Genre", visible=False) step_input = gr.Number(label="Step", value=0, visible=False) health_input = gr.Number(label="Health", value=100, visible=False) choice_input = gr.Textbox(label="Choice", visible=False) history_input = gr.Textbox(label="History JSON", value="[]", visible=False)
# Output fields story_output = gr.Textbox(label="Story") choices_output = gr.JSON(label="Choices") health_output = gr.Number(label="Health") step_output = gr.Number(label="Step") game_over_output = gr.Checkbox(label="Game Over") history_output = gr.Textbox(label="History JSON")
def api_start_game(genre: str): """Start a new interactive text adventure. Exposed as MCP tool.""" genre = genre.lower() if genre not in ["fantasy", "scifi", "cyberpunk"]: genre = "fantasy"
llm = get_llm() if not llm: result = generate_procedural_step(genre, 0, 100) return ( result["story"], result["choices"], result["health"], result["step"], result["game_over"], json.dumps(result.get("history", [])) )
instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet." story = generate_llm_story(format_prompt(genre, [], instruction)) if not story: result = generate_procedural_step(genre, 0, 100) return ( result["story"], result["choices"], result["health"], result["step"], result["game_over"], json.dumps(result.get("history", [])) )
history = [{"role": "narrator", "text": story}] choices_instruction = ( "Provide exactly 3 short, distinct choices for the player. " "Format: 1. [choice 1] | 2. [choice 2] | 3. [choice 3]" ) choices_text = generate_llm_story(format_prompt(genre, history, choices_instruction), max_tokens=60)
choices = _parse_choices(choices_text) if len(choices) < 2: choices = ["Explore the area", "Check your equipment", "Proceed carefully"]
return (story, choices[:3], 100, 1, False, json.dumps(history))
def api_make_choice(choice: str, genre: str, step: int, health: int, history_json: str): """Submit a player choice to advance the story. Exposed as MCP tool.""" try: history = json.loads(history_json) except Exception: history = []
llm = get_llm() step = int(step) health = int(health)
if not llm: result = generate_procedural_step(genre, step, health, choice) return ( result["story"], result["choices"], result["health"], result["step"], result["game_over"], json.dumps(result.get("history", history)) )
history.append({"role": "player", "text": choice})
health_delta = random.choice([-15, 0, 10]) new_health = max(0, min(100, health + health_delta))
if new_health <= 0: instruction = "The player has run out of health. Narrate a quick, dramatic end. Game Over." story = generate_llm_story(format_prompt(genre, history, instruction)) return ( story or "Your strength fails. The adventure ends in darkness.", [], 0, step + 1, True, json.dumps(history) )
if step >= 4: instruction = "Narrate the final glorious victory. The adventure ends in success." story = generate_llm_story(format_prompt(genre, history, instruction)) return ( story or "You have achieved your goal! You are victorious!", [], new_health, step + 1, True, json.dumps(history) )
instruction = "Narrate what happens next as a result of the player's choice." story = generate_llm_story(format_prompt(genre, history, instruction)) if not story: result = generate_procedural_step(genre, step, health, choice) return ( result["story"], result["choices"], result["health"], result["step"], result["game_over"], json.dumps(result.get("history", history)) )
history.append({"role": "narrator", "text": story})
choices_instruction = ( "Provide exactly 3 short, distinct choices. " "Format: 1. [choice 1] | 2. [choice 2] | 3. [choice 3]" ) choices_text = generate_llm_story(format_prompt(genre, history, choices_instruction), max_tokens=60)
choices = _parse_choices(choices_text) if len(choices) < 2: choices = ["Move forward", "Look around", "Rest a moment"]
return (story, choices[:3], new_health, step + 1, False, json.dumps(history))
# Register API endpoints gr.Button("Start Game").click( fn=api_start_game, inputs=[genre_input], outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output], api_name="start_game" )
gr.Button("Make Choice").click( fn=api_make_choice, inputs=[choice_input, genre_input, step_input, health_input, history_input], outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output], api_name="make_choice" )
return blocks
def _parse_choices(choices_text: str) -> List[str]: """Parse LLM choice output into a list of choices.""" choices = [] if "|" in choices_text: choices = [c.split(".")[-1].strip() for c in choices_text.split("|")] else: for line in choices_text.split("\n"): if "." in line or any(d in line for d in "123"): parts = line.split(".", 1) if len(parts) > 1: choices.append(parts[1].strip()) return choices
# ---------------------------------------------------------------------------# FastAPI App — Custom frontend + Gradio API# ---------------------------------------------------------------------------fastapi_app = FastAPI(title="TinyBard", docs_url="/docs")
@fastapi_app.get("/", response_class=HTMLResponse)async def homepage(): """Serve the retro CRT terminal frontend.""" index_path = STATIC_DIR / "index.html" if index_path.exists(): return index_path.read_text() return HTMLResponse("<h1>TinyBard retro terminal under construction!</h1>")
@fastapi_app.get("/api/model_status")async def model_status(): """Check if the LLM is loaded.""" llm = get_llm() return { "available": llm is not None, "model_path": MODEL_PATH, "fallback": _llm_failed }
# Mount static filesfastapi_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
# Mount Gradio app at /gradio — this creates the API + MCP endpointsgradio_blocks = create_gradio_app()mount_gradio_app(fastapi_app, gradio_blocks, path="/gradio")
# ---------------------------------------------------------------------------# Entrypoint# ---------------------------------------------------------------------------if __name__ == "__main__": import uvicorn port = int(os.environ.get("PORT", "7860")) log.info(f"Starting TinyBard on port {port}") log.info(f"Frontend: http://localhost:{port}/") log.info(f"Gradio API: http://localhost:{port}/gradio/") log.info(f"MCP schema: http://localhost:{port}/gradio/gradio_api/mcp/schema") uvicorn.run(fastapi_app, host="0.0.0.0", port=port)1234567# TinyBard — Micro Text Adventure Generator# Python 3.10+
gradio>=5.0numpy>=1.24llama-cpp-python>=0.3.0huggingface_hub>=0.201234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TinyBard — Micro Text Adventure</title> <link rel="stylesheet" href="/static/style.css"></head><body> <div class="crt-container"> <div class="crt-screen" id="screen"> <div class="scanlines"></div> <div class="vignette"></div> <div class="terminal" id="terminal"> <div class="terminal-header"> <span class="prompt">TINYBARD v1.0</span> <span class="status" id="health-bar">HEALTH: <span id="health-val">100</span></span> </div> <div class="terminal-body" id="output"> <div class="boot-sequence" id="boot"> <span class="line">> INITIALIZING NEURAL INTERFACE...</span> <span class="line">> LOADING NARRATIVE ENGINE...</span> <span class="line">> CONNECTING TO GRADIO SERVER...</span> <span class="line success">> CONNECTION ESTABLISHED</span> <span class="line">> SELECT GENRE TO BEGIN</span> </div> </div> <div class="genre-selector" id="genre-selector"> <div class="genre-option" data-genre="fantasy"> <span class="icon">⚔</span> FANTASY </div> <div class="genre-option" data-genre="scifi"> <span class="icon">🚀</span> SCI-FI </div> <div class="genre-option" data-genre="cyberpunk"> <span class="icon">🌆</span> CYBERPUNK </div> </div> <div class="choices-container" id="choices" style="display: none;"> <!-- Choices injected here --> </div> <div class="input-line" id="input-line" style="display: none;"> <span class="prompt-char">></span> <input type="text" id="cmd-input" autocomplete="off" spellcheck="false" /> <span class="cursor" id="cursor">_</span> </div> <div class="terminal-footer"> <span>TinyBard | gr.Server + MCP | Llama.cpp</span> <span id="model-status">MODEL: LOADING...</span> </div> </div> </div> <div class="crt-reflection"></div> </div> <script type="module" src="/static/main.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263/** * TinyBard — Frontend Client * Connects to the gr.Server backend via @gradio/client. * All game state is managed client-side and passed to the API. */
const GRADIO_CLIENT_URL = window.location.origin;
// ---------------------------------------------------------------------------// Game State// ---------------------------------------------------------------------------let gameState = { genre: "", step: 0, health: 100, history: [], gameActive: false};
// ---------------------------------------------------------------------------// DOM refs// ---------------------------------------------------------------------------const output = document.getElementById("output");const choicesEl = document.getElementById("choices");const genreSelector = document.getElementById("genre-selector");const inputLine = document.getElementById("input-line");const cmdInput = document.getElementById("cmd-input");const healthVal = document.getElementById("health-val");const modelStatus = document.getElementById("model-status");const boot = document.getElementById("boot");
// ---------------------------------------------------------------------------// Gradio Client// ---------------------------------------------------------------------------let gradioClient = null;const GRADIO_PATH = "/gradio";
async function initClient() { try { const { Client } = await import( "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js" ); gradioClient = await Client.connect(GRADIO_CLIENT_URL + GRADIO_PATH); modelStatus.textContent = "MODEL: CONNECTED"; modelStatus.style.color = "#00ff41"; } catch (e) { console.warn("Gradio client init failed, using fetch fallback:", e); gradioClient = null; modelStatus.textContent = "MODEL: FETCH MODE"; modelStatus.style.color = "#ffb000"; }}
async function apiCall(endpoint, payload) { if (gradioClient) { try { const result = await gradioClient.predict(endpoint, payload); return result.data; } catch (e) { console.warn("Gradio client call failed, falling back to fetch:", e); } } // Fallback: direct fetch to gradio API const resp = await fetch(`${GRADIO_CLIENT_URL}${GRADIO_PATH}/api/${endpoint}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: Object.values(payload) }) }); const json = await resp.json(); return json.data;}
// ---------------------------------------------------------------------------// UI Helpers// ---------------------------------------------------------------------------function scrollToBottom() { output.scrollTop = output.scrollHeight;}
function appendOutput(html, className = "") { const el = document.createElement("div"); el.className = className; el.innerHTML = html; output.appendChild(el); scrollToBottom();}
function clearBoot() { if (boot) boot.remove();}
function updateHealth(hp) { gameState.health = hp; healthVal.textContent = hp; if (hp <= 25) healthVal.style.color = "#ff0040"; else if (hp <= 50) healthVal.style.color = "#ffb000"; else healthVal.style.color = "#00ff41";}
function showChoices(choices) { choicesEl.innerHTML = ""; choicesEl.style.display = "flex";
choices.forEach((choice, i) => { const btn = document.createElement("button"); btn.className = "choice-btn"; btn.textContent = choice; btn.addEventListener("click", () => handleChoice(choice)); choicesEl.appendChild(btn); });}
function hideChoices() { choicesEl.style.display = "none"; choicesEl.innerHTML = "";}
function showInput() { inputLine.style.display = "flex"; cmdInput.focus();}
function hideInput() { inputLine.style.display = "none";}
// ---------------------------------------------------------------------------// Game Logic// ---------------------------------------------------------------------------async function startGame(genre) { gameState = { genre, step: 0, health: 100, history: [], gameActive: true }; genreSelector.style.display = "none"; clearBoot();
appendOutput(`<span class="narrator-prefix">> STARTING ${genre.toUpperCase()} ADVENTURE...</span>`, "line amber"); updateHealth(100);
try { const data = await apiCall("/start_game", { genre });
gameState.step = data.step || 1; gameState.history = data.history || [];
const storyEl = document.createElement("div"); storyEl.className = "story-text"; storyEl.textContent = data.story; output.appendChild(storyEl);
if (data.game_over) { endGame(data); } else { showChoices(data.choices); } } catch (e) { appendOutput(`<span class="error">ERROR: ${e.message}</span>`, "line error"); console.error(e); } scrollToBottom();}
async function handleChoice(choice) { if (!gameState.gameActive) return;
hideChoices(); appendOutput(`<span class="player-action">> You chose: ${choice}</span>`, "player-action");
try { const data = await apiCall("/make_choice", { choice, genre: gameState.genre, step: gameState.step, health: gameState.health, history_json: JSON.stringify(gameState.history) });
gameState.step = data.step || gameState.step + 1; gameState.history = data.history || gameState.history; updateHealth(data.health ?? gameState.health);
const storyEl = document.createElement("div"); storyEl.className = "story-text"; storyEl.textContent = data.story; output.appendChild(storyEl);
if (data.game_over) { endGame(data); } else { showChoices(data.choices); } } catch (e) { appendOutput(`<span class="error">ERROR: ${e.message}</span>`, "line error"); console.error(e); } scrollToBottom();}
function endGame(data) { gameState.gameActive = false; hideChoices();
const isWin = data.health > 0; const className = isWin ? "game-over-win" : "game-over-lose"; const label = isWin ? "★ VICTORY ★" : "☠ GAME OVER ☠";
appendOutput(`<div class="${className}">${label}<br><small>Final Health: ${data.health}</small></div>`, "");
// New game button const btn = document.createElement("button"); btn.className = "new-game-btn"; btn.textContent = "[ NEW ADVENTURE ]"; btn.addEventListener("click", resetGame); choicesEl.style.display = "flex"; choicesEl.appendChild(btn);}
function resetGame() { output.innerHTML = ""; hideChoices(); gameState = { genre: "", step: 0, health: 100, history: [], gameActive: false }; healthVal.textContent = "100"; healthVal.style.color = "#00ff41"; genreSelector.style.display = "flex";}
// ---------------------------------------------------------------------------// Event Listeners// ---------------------------------------------------------------------------document.querySelectorAll(".genre-option").forEach(el => { el.addEventListener("click", () => { const genre = el.dataset.genre; startGame(genre); });});
cmdInput.addEventListener("keydown", (e) => { if (e.key === "Enter" && cmdInput.value.trim()) { handleChoice(cmdInput.value.trim()); cmdInput.value = ""; }});
// ---------------------------------------------------------------------------// Boot// ---------------------------------------------------------------------------(async () => { await initClient();
// Check model status try { const resp = await fetch(`${GRADIO_CLIENT_URL}/api/model_status`); const status = await resp.json(); if (status.available) { modelStatus.textContent = "MODEL: READY"; modelStatus.style.color = "#00ff41"; } else { modelStatus.textContent = "MODEL: FALLBACK"; modelStatus.style.color = "#ffb000"; } } catch { modelStatus.textContent = "MODEL: UNKNOWN"; modelStatus.style.color = "#666"; }})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394/* TinyBard CRT Terminal Theme */
:root { --green: #00ff41; --green-dim: #00aa2a; --green-dark: #004d13; --green-glow: rgba(0, 255, 65, 0.15); --amber: #ffb000; --red: #ff0040; --bg: #0a0a0a; --terminal-bg: #0d1117; --scanline-opacity: 0.03;}
* { margin: 0; padding: 0; box-sizing: border-box; }
@font-face { font-family: 'MonoFallback'; src: local('JetBrains Mono'), local('Fira Code'), local('SF Mono'), local('Menlo'), local('monospace');}
body { background: var(--bg); font-family: 'MonoFallback', monospace; color: var(--green); min-height: 100vh; display: flex; align-items: center; justify-content: center; overflow: hidden;}
/* CRT Monitor Container */.crt-container { width: 90vw; max-width: 900px; height: 85vh; max-height: 700px; position: relative; background: #1a1a2e; border-radius: 30px; padding: 25px; box-shadow: 0 0 80px rgba(0, 255, 65, 0.08), inset 0 0 60px rgba(0, 0, 0, 0.5), 0 20px 60px rgba(0, 0, 0, 0.8);}
.crt-screen { width: 100%; height: 100%; background: var(--terminal-bg); border-radius: 15px; overflow: hidden; position: relative; border: 2px solid #222;}
/* Scanlines overlay */.scanlines { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: repeating-linear-gradient( 0deg, transparent, transparent 2px, rgba(0, 0, 0, var(--scanline-opacity)) 2px, rgba(0, 0, 0, var(--scanline-opacity)) 4px ); pointer-events: none; z-index: 10;}
/* Vignette effect */.vignette { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: radial-gradient(ellipse at center, transparent 60%, rgba(0,0,0,0.4) 100%); pointer-events: none; z-index: 10;}
/* CRT reflection/glare */.crt-reflection { position: absolute; top: 5%; left: 5%; width: 40%; height: 30%; background: linear-gradient( 135deg, rgba(255, 255, 255, 0.03) 0%, transparent 100% ); pointer-events: none; z-index: 20; border-radius: 50%;}
/* Terminal Layout */.terminal { width: 100%; height: 100%; display: flex; flex-direction: column; padding: 15px 20px; position: relative; z-index: 5;}
.terminal-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 10px; border-bottom: 1px solid var(--green-dark); margin-bottom: 10px; font-size: 0.75rem; color: var(--green-dim); text-transform: uppercase; letter-spacing: 2px;}
.terminal-header .status { color: var(--amber); }#health-val { color: var(--green); font-weight: bold; }
/* Terminal output area */.terminal-body { flex: 1; overflow-y: auto; overflow-x: hidden; padding-right: 10px; font-size: 0.85rem; line-height: 1.6; text-shadow: 0 0 5px var(--green-glow); scroll-behavior: smooth;}
.terminal-body::-webkit-scrollbar { width: 6px; }.terminal-body::-webkit-scrollbar-track { background: transparent; }.terminal-body::-webkit-scrollbar-thumb { background: var(--green-dark); border-radius: 3px;}
/* Text styles */.line { display: block; margin-bottom: 3px; opacity: 0; animation: typeIn 0.5s forwards;}.line.success { color: var(--green); }.line.error { color: var(--red); }.line.amber { color: var(--amber); }
.story-text { display: block; margin: 12px 0; padding: 10px 15px; border-left: 2px solid var(--green-dim); background: rgba(0, 255, 65, 0.03); white-space: pre-wrap; animation: fadeSlideIn 0.6s ease-out;}
.narrator-prefix { color: var(--amber); font-weight: bold;}
.player-action { display: block; color: var(--green-dim); margin: 5px 0; font-style: italic;}
.game-over-win { color: var(--green); text-shadow: 0 0 20px var(--green); font-size: 1.1rem; text-align: center; padding: 20px; animation: pulse 2s infinite;}
.game-over-lose { color: var(--red); text-shadow: 0 0 20px var(--red); font-size: 1.1rem; text-align: center; padding: 20px; animation: pulse 2s infinite;}
/* Genre selector */.genre-selector { display: flex; gap: 15px; padding: 15px 0; justify-content: center;}
.genre-option { padding: 12px 25px; border: 1px solid var(--green-dark); border-radius: 4px; cursor: pointer; transition: all 0.2s; text-transform: uppercase; letter-spacing: 1px; font-size: 0.8rem; color: var(--green-dim);}
.genre-option:hover { background: var(--green-dark); color: var(--green); border-color: var(--green); text-shadow: 0 0 10px var(--green); box-shadow: 0 0 15px rgba(0, 255, 65, 0.2);}
.genre-option .icon { margin-right: 8px; font-size: 1rem; }
/* Choice buttons */.choices-container { display: flex; flex-direction: column; gap: 8px; padding: 10px 0;}
.choice-btn { display: block; padding: 10px 15px; border: 1px solid var(--green-dark); border-radius: 3px; background: transparent; color: var(--green-dim); font-family: 'MonoFallback', monospace; font-size: 0.8rem; cursor: pointer; text-align: left; transition: all 0.15s; text-shadow: 0 0 3px var(--green-glow);}
.choice-btn:hover { background: rgba(0, 255, 65, 0.08); border-color: var(--green); color: var(--green); padding-left: 25px;}
.choice-btn::before { content: '> '; color: var(--amber);}
/* Input line */.input-line { display: flex; align-items: center; padding: 10px 0 5px; border-top: 1px solid var(--green-dark); margin-top: 5px;}
.prompt-char { color: var(--amber); margin-right: 8px; font-weight: bold;}
#cmd-input { flex: 1; background: transparent; border: none; color: var(--green); font-family: 'MonoFallback', monospace; font-size: 0.85rem; outline: none; caret-color: transparent;}
.cursor { color: var(--green); animation: blink 0.8s step-end infinite;}
/* Terminal footer */.terminal-footer { display: flex; justify-content: space-between; padding-top: 8px; border-top: 1px solid #1a1a2e; margin-top: 8px; font-size: 0.65rem; color: #444; letter-spacing: 1px;}
#model-status { color: var(--green-dark); }
/* Health bar visual */.health-bar-visual { width: 100%; height: 4px; background: #1a1a2e; border-radius: 2px; margin-top: 5px; overflow: hidden;}
.health-bar-fill { height: 100%; background: var(--green); transition: width 0.5s ease, background-color 0.5s; border-radius: 2px;}
.health-bar-fill.low { background: var(--red); }.health-bar-fill.mid { background: var(--amber); }
/* New game button */.new-game-btn { display: inline-block; padding: 8px 20px; border: 1px solid var(--green-dark); border-radius: 3px; background: transparent; color: var(--green-dim); font-family: 'MonoFallback', monospace; font-size: 0.75rem; cursor: pointer; text-transform: uppercase; letter-spacing: 1px; margin-top: 10px; transition: all 0.2s;}
.new-game-btn:hover { background: var(--green-dark); color: var(--green); border-color: var(--green);}
/* Animations */@keyframes typeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); }}
@keyframes fadeSlideIn { from { opacity: 0; transform: translateX(-10px); } to { opacity: 1; transform: translateX(0); }}
@keyframes blink { 50% { opacity: 0; }}
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.6; }}
/* Flicker effect on load */.crt-screen { animation: crtOn 0.5s ease-out;}
@keyframes crtOn { 0% { opacity: 0; transform: scaleY(0.01); } 40% { opacity: 1; transform: scaleY(0.01); } 60% { transform: scaleY(1.05); } 80% { transform: scaleY(0.98); } 100% { transform: scaleY(1); }}
/* Mobile responsive */@media (max-width: 600px) { .crt-container { width: 95vw; height: 90vh; padding: 12px; border-radius: 15px; } .genre-selector { flex-direction: column; gap: 8px; } .genre-option { text-align: center; } .terminal-body { font-size: 0.75rem; }}.agents/tasks/TASK.2026-06-08.mdAdded+18
projects/tinybard/.gitignoreAdded+10
projects/tinybard/README.mdAdded+90
projects/tinybard/__init__.pyAdded+1
projects/tinybard/app.pyAdded+427
projects/tinybard/requirements.txtAdded+7
projects/tinybard/static/index.htmlAdded+65
projects/tinybard/static/main.jsAdded+263
projects/tinybard/static/style.cssAdded+394