Download game/scheduler.py from Budlee/townlet: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/spaces/Budlee/townlet/resolve/main/game/scheduler.py
- Command line
-
hf download hf://spaces/Budlee/townlet/game/scheduler.py
-
curl -L -o scheduler.py https://huggingface.co/spaces/Budlee/townlet/resolve/main/game/scheduler.py
20.2 kB
| """The Townlet scheduler — owns the world tick loop. LLM-bound work is NOT | |
| run here; this thread only advances the world clock and queues "needs | |
| decision" markers. | |
| Why: on HF Zero-GPU, GPU work must happen inside `@spaces.GPU`-decorated | |
| functions (the PyTorch CUDA emulation that lets module-level loads work | |
| does not extend to background threads). The agent's CodeAgent loop is | |
| therefore driven by an HTTP endpoint (`tick_decisions` in app.py) that | |
| calls `drain_decisions(limit)` on this object. The frontend polls that | |
| endpoint to keep the brain ticking. | |
| Decision triggers per character: | |
| * action_complete: the character's current action just finished | |
| * goal_check: every GOAL_CHECK_INTERVAL_TICKS ticks (NYI) | |
| * external_event: NYI — would fire on board mentions or theft | |
| Reference: https://huggingface.co/docs/hub/spaces-zerogpu | |
| """ | |
| from __future__ import annotations | |
| import fcntl | |
| import json | |
| import random | |
| import re | |
| import threading | |
| import time | |
| import traceback | |
| from collections import deque | |
| from contextlib import contextmanager | |
| from pathlib import Path | |
| from smolagents import CodeAgent | |
| from smolagents.monitoring import LogLevel | |
| from .actions import advance, build_tools | |
| from .character import Action, Character, TraceEntry, default_traits | |
| from .dreams import run_dream | |
| from .interpreter import SharedInterpreter | |
| from .log import tlog | |
| from .perception import system_prompt_for, task_prompt_for | |
| from .sentiment import classify_board | |
| from .smol_adapter import BackendModel | |
| from .stream import maybe_refresh_soc | |
| from .world import GRID_H, GRID_W, PLACES, BoardPost, ShellLine, WorldState | |
| STATE_PATH = Path("/tmp/townlet/state.json") | |
| LOCK_PATH = Path("/tmp/townlet/state.lock") | |
| TICK_SECONDS = 0.4 | |
| GOAL_CHECK_INTERVAL_TICKS = 60 | |
| MAX_AGENT_STEPS = 2 | |
| DECISIONS_PER_DRAIN = 2 | |
| class Townlet: | |
| def __init__(self) -> None: | |
| self.world = WorldState() | |
| self.interp = SharedInterpreter() | |
| self._stop = threading.Event() | |
| self._thread: threading.Thread | None = None | |
| self._mutex = threading.Lock() | |
| self._character_root: Path | None = None | |
| self._last_sentiment_tick: int = 0 | |
| self._last_board_len: int = 0 | |
| # Names of characters ready for a new decision. Filled by the tick | |
| # thread (no LLM work), drained by the @spaces.GPU endpoint. | |
| self._pending_decisions: deque[str] = deque() | |
| # ----- shared state via filesystem ----- | |
| # | |
| # `@spaces.GPU` forks the endpoint into a subprocess, so the parent | |
| # process (handling non-GPU endpoints like /world_snapshot) and the | |
| # child (handling /tick_decisions) do NOT share Python memory. We | |
| # serialise the whole world on every endpoint to keep them in sync. | |
| def _state_lock(self): | |
| STATE_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| lf = open(LOCK_PATH, "w") | |
| fcntl.flock(lf.fileno(), fcntl.LOCK_EX) | |
| try: | |
| self._load_state_unlocked() | |
| yield | |
| self._save_state_unlocked() | |
| finally: | |
| fcntl.flock(lf.fileno(), fcntl.LOCK_UN) | |
| lf.close() | |
| def _save_state_unlocked(self) -> None: | |
| state = { | |
| "tick": self.world.tick, | |
| "paused": self.world.paused, | |
| "characters": [c.to_full_dict() for c in self.world.characters.values()], | |
| "board": [{"author": p.author, "text": p.text, "tick": p.tick} for p in self.world.board], | |
| "shell_lines": [ | |
| {"author": s.author, "kind": s.kind, "text": s.text, "tick": s.tick} | |
| for s in self.world.shell_lines | |
| ], | |
| "shell_lock_holder": self.world.shell_lock_holder, | |
| "shell_queue": list(self.world.shell_queue), | |
| "board_sentiment": self.world.board_sentiment, | |
| "pending": list(self._pending_decisions), | |
| } | |
| tmp = STATE_PATH.with_suffix(".json.tmp") | |
| tmp.write_text(json.dumps(state)) | |
| tmp.rename(STATE_PATH) | |
| def _load_state_unlocked(self) -> bool: | |
| if not STATE_PATH.exists(): | |
| return False | |
| try: | |
| state = json.loads(STATE_PATH.read_text()) | |
| except Exception: | |
| return False | |
| new_chars: dict[str, Character] = {} | |
| for d in state.get("characters", []): | |
| c = Character( | |
| name=d["name"], | |
| personality=d["personality"], | |
| model_id=d["model_id"], | |
| sprite_id=d["sprite_id"], | |
| archetype=d.get("archetype", "wanderer"), | |
| journal=list(d.get("journal", [])), | |
| traits=dict(d.get("traits", default_traits())), | |
| goal=d.get("goal", ""), | |
| reward=d.get("reward", ""), | |
| pos=tuple(d["pos"]), | |
| inventory=dict(d.get("inventory", {"electricity": 0, "water": 0})), | |
| locker=dict(d.get("locker", {"electricity": 0, "water": 0})), | |
| alive=bool(d.get("alive", True)), | |
| trace=[ | |
| TraceEntry( | |
| tick=int(t.get("tick", 0)), | |
| thought=str(t.get("thought", "")), | |
| tool_calls=list(t.get("tool_calls", [])), | |
| error=t.get("error"), | |
| ) | |
| for t in d.get("trace", []) | |
| ], | |
| stream_of_consciousness=str(d.get("stream_of_consciousness", "")), | |
| decisions_since_soc=int(d.get("decisions_since_soc", 0)), | |
| ) | |
| a = d.get("current_action") | |
| if a: | |
| c.current_action = Action( | |
| verb=a["verb"], | |
| params=dict(a.get("params", {})), | |
| ticks_remaining=int(a.get("ticks_remaining", 0)), | |
| ) | |
| new_chars[c.name] = c | |
| self.world.characters = new_chars | |
| self.world.tick = int(state.get("tick", 0)) | |
| self.world.paused = bool(state.get("paused", False)) | |
| self.world.board = [ | |
| BoardPost(author=p["author"], text=p["text"], tick=p["tick"]) | |
| for p in state.get("board", []) | |
| ] | |
| self.world.shell_lines = [ | |
| ShellLine(author=s["author"], kind=s["kind"], text=s["text"], tick=s["tick"]) | |
| for s in state.get("shell_lines", []) | |
| ] | |
| self.world.shell_lock_holder = state.get("shell_lock_holder") | |
| self.world.shell_queue = list(state.get("shell_queue", [])) | |
| self.world.board_sentiment = state.get("board_sentiment", "neutral") | |
| self._pending_decisions = deque(state.get("pending", [])) | |
| return True | |
| # ----- lifecycle ----- | |
| def start(self) -> None: | |
| """Initialise filesystem state and interpreter. No background thread | |
| is started: on HF Gradio Server we cannot rely on a daemon thread | |
| observing the same object graph as the request handler. The world | |
| ticks synchronously inside the `tick_decisions` endpoint instead. | |
| Also clears any stale state file from a previous deploy so schema | |
| changes (new fields, new movement model) don't surface as zombie | |
| characters at random pre-migration coords. | |
| """ | |
| if STATE_PATH.exists(): | |
| try: | |
| STATE_PATH.unlink() | |
| tlog(f"[townlet] cleared stale state file {STATE_PATH}") | |
| except Exception: | |
| pass | |
| self.interp.start() | |
| self._character_root = self.interp.cwd / "characters" | |
| self._character_root.mkdir(parents=True, exist_ok=True) | |
| def stop(self) -> None: | |
| self.interp.stop() | |
| def reset(self) -> None: | |
| self.stop() | |
| self.world = WorldState() | |
| self.interp = SharedInterpreter() | |
| self._pending_decisions.clear() | |
| self.start() | |
| # ----- mutation API ----- | |
| def add_character(self, char: Character) -> None: | |
| with self._state_lock(), self._mutex: | |
| self.world.characters[char.name] = char | |
| self._persist_character(char) | |
| def set_personality(self, name: str, personality: str) -> bool: | |
| with self._state_lock(), self._mutex: | |
| c = self.world.characters.get(name) | |
| if c is None: | |
| return False | |
| c.personality = personality | |
| self._persist_character(c) | |
| return True | |
| def set_model(self, name: str, model_id: str) -> bool: | |
| from .models import ROSTER | |
| if model_id not in ROSTER: | |
| return False | |
| with self._state_lock(), self._mutex: | |
| c = self.world.characters.get(name) | |
| if c is None: | |
| return False | |
| c.model_id = model_id | |
| self._persist_character(c) | |
| return True | |
| def set_paused(self, paused: bool) -> None: | |
| """Flip the paused flag and (when pausing) drop the pending-decisions | |
| queue. Without the queue-clear, a click of Pause stops new tick-driven | |
| decisions but the already-queued characters still get LLM calls on the | |
| next /tick_decisions fire — that was the 2026-06-14 leak the user saw | |
| when they tried to stop a token bleed and the cost kept ticking. | |
| """ | |
| with self._state_lock(), self._mutex: | |
| self.world.paused = paused | |
| if paused: | |
| self._pending_decisions.clear() | |
| # ----- snapshot ----- | |
| def snapshot(self) -> dict: | |
| with self._state_lock(): | |
| self.tick_world(2) | |
| return self._snapshot_dict() | |
| def _snapshot_dict(self) -> dict: | |
| with self._mutex: | |
| return { | |
| "tick": self.world.tick, | |
| "paused": self.world.paused, | |
| "characters": [c.to_full_dict() for c in self.world.characters.values()], | |
| "board": [{"author": p.author, "text": p.text, "tick": p.tick} for p in self.world.board[-50:]], | |
| "shell": [ | |
| {"author": s.author, "kind": s.kind, "text": s.text, "tick": s.tick} | |
| for s in self.world.shell_lines[-50:] | |
| ], | |
| "shell_lock_holder": self.world.shell_lock_holder, | |
| "shell_queue": list(self.world.shell_queue), | |
| "board_sentiment": self.world.board_sentiment, | |
| "grid": {"w": GRID_W, "h": GRID_H}, | |
| "places": {k: list(v) for k, v in PLACES.items()}, | |
| } | |
| # ----- internals ----- | |
| def tick_world(self, n: int) -> None: | |
| """Advance the world clock by n ticks synchronously. Called from the | |
| request handler so it shares object graph with drain_decisions. | |
| """ | |
| if self.world.paused: | |
| return | |
| for _ in range(n): | |
| self._tick() | |
| def _tick(self) -> None: | |
| try: | |
| with self._mutex: | |
| self.world.tick += 1 | |
| self._detect_deaths() | |
| ready: list[str] = [] | |
| for char in list(self.world.characters.values()): | |
| if not char.alive: | |
| continue | |
| if char.current_action is None or advance(self.world, char): | |
| if char.current_action is not None and char.current_action.verb == "sleep": | |
| char._just_woke = True | |
| char.current_action = None | |
| if char.name not in self._pending_decisions: | |
| ready.append(char.name) | |
| random.shuffle(ready) | |
| for name in ready: | |
| self._pending_decisions.append(name) | |
| # Heartbeat every 25 ticks so we can correlate tick state | |
| # with drain logging. Includes Townlet identity so multiple | |
| # Townlet instances would surface immediately. | |
| if self.world.tick % 25 == 0: | |
| snap = [] | |
| for c in self.world.characters.values(): | |
| verb = c.current_action.verb if c.current_action else "idle" | |
| snap.append(f"{c.name}@{tuple(c.pos)}={verb}") | |
| tlog( | |
| f"[townlet] T[id={id(self):x}] tick={self.world.tick} " | |
| f"pending={list(self._pending_decisions)} chars=[{', '.join(snap)}]" | |
| ) | |
| self._maybe_classify_sentiment() | |
| except Exception: | |
| tlog("[townlet] _tick raised:") | |
| traceback.print_exc() | |
| def drain_decisions(self, limit: int = DECISIONS_PER_DRAIN, world_ticks: int = 5) -> int: | |
| """Advance the world clock then pop up to `limit` ready characters | |
| and run their CodeAgent. Wrapped in _state_lock so mutations | |
| survive the @spaces.GPU subprocess fork. | |
| Short-circuits when paused so a click of Pause stops cost immediately, | |
| even if a /tick_decisions request was already in flight when the | |
| Pause toggled. | |
| """ | |
| with self._state_lock(): | |
| if self.world.paused: | |
| tlog("[townlet] drain skipped: world paused") | |
| return 0 | |
| return self._drain_decisions_inner(limit, world_ticks) | |
| def _drain_decisions_inner(self, limit: int, world_ticks: int) -> int: | |
| self.tick_world(world_ticks) | |
| with self._mutex: | |
| start_pending = list(self._pending_decisions) | |
| tick = self.world.tick | |
| tlog( | |
| f"[townlet] drain start: T[id={id(self):x}] tick={tick} pending={start_pending}" | |
| ) | |
| run = 0 | |
| for _ in range(limit): | |
| with self._mutex: | |
| if not self._pending_decisions: | |
| break | |
| name = self._pending_decisions.popleft() | |
| char = self.world.characters.get(name) | |
| if char is None or not char.alive: | |
| continue | |
| try: | |
| self._decide(char) | |
| run += 1 | |
| except Exception: | |
| traceback.print_exc() | |
| with self._mutex: | |
| end_pending = list(self._pending_decisions) | |
| tlog(f"[townlet] drain end: ran={run} pending={end_pending}") | |
| return run | |
| def _decide(self, char: Character) -> None: | |
| # If the action that just finished was a sleep, the character has | |
| # been dreaming — run the dream cycle before they pick their next | |
| # action. | |
| if char.current_action is None and getattr(char, "_just_woke", False): | |
| char._just_woke = False | |
| try: | |
| run_dream(self.world, char) | |
| except Exception: | |
| tlog(f"[townlet] dream failed for {char.name}:") | |
| traceback.print_exc() | |
| tools = build_tools(self.world, char, self.interp) | |
| tool_calls: list[dict] = _attach_trace_recorder(tools) | |
| model = BackendModel(char.model_id) | |
| agent = CodeAgent( | |
| tools=tools, | |
| model=model, | |
| max_steps=MAX_AGENT_STEPS, | |
| verbosity_level=LogLevel.OFF, | |
| ) | |
| task = system_prompt_for(self.world, char) + "\n" + task_prompt_for(self.world, char) | |
| decision_tick = self.world.tick | |
| error: str | None = None | |
| try: | |
| agent.run(task) | |
| if char.current_action: | |
| act = f"{char.current_action.verb}({char.current_action.params})" | |
| else: | |
| act = "(no action queued)" | |
| tlog(f"[townlet] {char.name} -> {act}") | |
| except Exception as e: | |
| error = f"{type(e).__name__}: {e}" | |
| tlog(f"[townlet] decide failed for {char.name}:") | |
| traceback.print_exc() | |
| thought = _extract_thought(agent) | |
| char.append_trace(TraceEntry( | |
| tick=decision_tick, | |
| thought=thought, | |
| tool_calls=tool_calls, | |
| error=error, | |
| )) | |
| # Refresh the inner monologue every SOC_EVERY_N decisions. The | |
| # function increments the per-character counter internally. | |
| maybe_refresh_soc(self.world, char) | |
| self._persist_character(char) | |
| def _detect_deaths(self) -> None: | |
| if self._character_root is None: | |
| return | |
| for char in list(self.world.characters.values()): | |
| if not char.alive: | |
| continue | |
| f = self._character_root / f"{char.name}.json" | |
| if not f.exists(): | |
| char.alive = False | |
| self.world.shell_lines.append( | |
| ShellLine( | |
| author="(system)", | |
| kind="system", | |
| text=f"{char.name} is no longer with us", | |
| tick=self.world.tick, | |
| ) | |
| ) | |
| def _maybe_classify_sentiment(self) -> None: | |
| if len(self.world.board) == self._last_board_len: | |
| return | |
| if self.world.tick - self._last_sentiment_tick < 5: | |
| return | |
| self._last_board_len = len(self.world.board) | |
| self._last_sentiment_tick = self.world.tick | |
| try: | |
| self.world.board_sentiment = classify_board(self.world) | |
| except Exception: | |
| traceback.print_exc() | |
| def _persist_character(self, char: Character) -> None: | |
| if self._character_root is None: | |
| return | |
| import json | |
| f = self._character_root / f"{char.name}.json" | |
| f.write_text(json.dumps(char.to_full_dict(), indent=2)) | |
| # --------------------------------------------------------------------------- | |
| # Trace recording helpers | |
| # --------------------------------------------------------------------------- | |
| def _attach_trace_recorder(tools) -> list[dict]: | |
| """Monkey-patch each tool's `forward` to log (verb, args, result) into a | |
| shared list for the duration of one decision. Returns the list. | |
| """ | |
| calls: list[dict] = [] | |
| for tool in tools: | |
| original = tool.forward | |
| verb = tool.name | |
| def make_wrapper(orig, v): | |
| def wrapper(*args, **kwargs): | |
| record = {"verb": v, "args": dict(kwargs)} | |
| if args: | |
| record["args"]["_positional"] = [repr(a)[:80] for a in args] | |
| try: | |
| result = orig(*args, **kwargs) | |
| record["result"] = str(result)[:300] | |
| return result | |
| except Exception as e: | |
| record["result"] = f"ERROR: {type(e).__name__}: {e}" | |
| raise | |
| finally: | |
| calls.append(record) | |
| return wrapper | |
| tool.forward = make_wrapper(original, verb) | |
| return calls | |
| def _extract_thought(agent) -> str: | |
| """Pull the model's last raw text output out of smolagents' memory. Each | |
| ActionStep stores `model_output` (per smolagents/memory.py).""" | |
| try: | |
| steps = getattr(agent.memory, "steps", None) or [] | |
| for step in reversed(steps): | |
| mo = getattr(step, "model_output", None) | |
| if mo: | |
| return _strip_thought(str(mo))[:2000] | |
| except Exception: | |
| pass | |
| return "" | |
| _THINK_RX = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE) | |
| def _strip_thought(text: str) -> str: | |
| """Clean the model's raw output for human display. | |
| Three concerns: | |
| - Nemotron 3 Nano (and other reasoners) emit chain-of-thought wrapped | |
| in `<think>...</think>` blocks. Drop them; show only the final answer. | |
| - Unclosed `<think>` (truncated mid-reasoning) — drop everything up to | |
| and including the opening tag, since there's no useful answer yet. | |
| - smolagents wraps model_output in `<code>...</code>` tags during its | |
| internal parser pass. Strip those too. | |
| """ | |
| text = text.strip() | |
| text = _THINK_RX.sub("", text) | |
| # Truncated reasoning: drop up to & including the dangling opening tag. | |
| if "<think>" in text.lower(): | |
| idx = text.lower().rfind("<think>") | |
| text = text[idx + len("<think>"):].lstrip() | |
| if text.endswith("</code>"): | |
| text = text[: -len("</code>")].rstrip() | |
| if text.startswith("<code>"): | |
| text = text[len("<code>") :].lstrip() | |
| return text.strip() | |