Add game end status with an end_game DM tool and automatic 0-HP detection

Games now have a status/ended_reason pair. The DM can call the new
end_game tool when the story reaches a real conclusion (victory,
defeat, or a resolved one-shot), and the backend independently ends
the game whenever a character's HP drops to 0 or below, regardless of
whether the DM narrates it. The frontend shows a banner and a
"Beendet" badge once a game ends.

HP moves from the freeform combat_stats bag into dedicated
current_hp/max_hp columns on Character, since reliably detecting 0 HP
requires a real integer rather than parsing strings like "3/10" out of
an LLM-authored key/value dict. Also fixed combat_stats to fully
replace on each upsert instead of merging, matching its documented
contract — the merge was leaving stale keys (old HP/TP text) behind
after the model stopped sending them.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Thorsten
2026-09-01 17:44:46 +02:00
parent 2b99451fdf
commit 8da834c5c1
17 changed files with 196 additions and 8 deletions
+34 -1
View File
@@ -9,7 +9,7 @@ from app.config import settings
from app.llm.client import get_dm_system_prompt, get_llm_client
from app.llm.context import build_context
from app.llm.json_utils import fix_double_escaped_unicode
from app.llm.tools import character_sheet, dice
from app.llm.tools import character_sheet, dice, end_game
from app.models.game import Game
from app.models.message import Message
from app.rag.retrieval import build_rag_block
@@ -22,6 +22,7 @@ MAX_TOKENS = 4096
TOOLS = [
{"type": "function", "function": dice.TOOL_SCHEMA},
{"type": "function", "function": character_sheet.TOOL_SCHEMA},
{"type": "function", "function": end_game.TOOL_SCHEMA},
]
@@ -35,6 +36,8 @@ async def _execute_tool_call(
return dice.roll(tool_input["notation"])
if tool_name == "upsert_character_sheet":
return await character_sheet.upsert(session, game_id, tool_input)
if tool_name == "end_game":
return await end_game.end(session, game_id, tool_input)
return {"error": f"Unknown tool {tool_name!r}"}
except Exception as exc: # noqa: BLE001
logger.warning("Tool call %s failed: %s", tool_name, exc)
@@ -42,11 +45,30 @@ async def _execute_tool_call(
return {"error": str(exc)}
async def _check_hp_game_over(session: AsyncSession, game_id: uuid.UUID, result: dict) -> str | None:
"""After an upsert_character_sheet call, auto-ends the game if the character it touched
dropped to 0 HP or below. Returns the end reason if the game was just ended, else None."""
current_hp = result.get("current_hp")
if current_hp is None or current_hp > 0:
return None
game = await session.get(Game, game_id)
if game is None or game.status == "ended":
return None
reason = f"{result.get('name', 'Ein Charakter')} ist bei {current_hp} Trefferpunkten zusammengebrochen."
game.status = "ended"
game.ended_reason = reason
await session.commit()
return reason
async def run_dm_turn(
session: AsyncSession,
game_id: uuid.UUID,
latest_player_message: str | None = None,
on_roll: Callable[[str], Awaitable[None]] | None = None,
on_game_ended: Callable[[str], Awaitable[None]] | None = None,
) -> Message:
client = get_llm_client()
system_prompt = get_dm_system_prompt()
@@ -90,6 +112,17 @@ async def run_dm_turn(
if tool_call.function.name == "roll_dice" and on_roll is not None:
await on_roll(tool_input.get("notation", ""))
result = await _execute_tool_call(session, game_id, tool_call.function.name, tool_input)
end_reason = None
if tool_call.function.name == "end_game" and "reason" in result:
end_reason = result["reason"]
elif tool_call.function.name == "upsert_character_sheet":
end_reason = await _check_hp_game_over(session, game_id, result)
if end_reason:
result = {**result, "game_ended": True, "end_reason": end_reason}
if end_reason and on_game_ended is not None:
await on_game_ended(end_reason)
messages.append(
{
"role": "tool",