Files
Thorsten 8da834c5c1 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>
2026-09-01 17:44:46 +02:00

147 lines
6.4 KiB
Python

import uuid
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.character import Character
from app.models.game import GameParticipant
from app.models.user import User
TOOL_SCHEMA = {
"name": "upsert_character_sheet",
"description": (
"Create or update a player's character sheet as facts about them are confirmed or change during play "
"(name, race, class, ability stats, combat stats, abilities, equipment, backstory). Call this "
"proactively as soon as details are settled — do not wait until the end of the session."
),
"parameters": {
"type": "object",
"properties": {
"player_name": {
"type": "string",
"description": "The real first name of the player this character belongs to, exactly as they introduced themselves.",
},
"character_id": {
"type": "string",
"description": "Omit when creating a new character. Provide the existing character's id when updating one.",
},
"name": {"type": "string"},
"race": {"type": "string"},
"char_class": {"type": "string"},
"stats": {
"type": "object",
"description": "Ability scores, e.g. {\"STR\": 15, \"DEX\": 12, \"CON\": 14, \"INT\": 10, \"WIS\": 8, \"CHA\": 13}",
},
"current_hp": {
"type": "integer",
"description": (
"Current hit points. Always send this together with max_hp whenever HP changes "
"(damage, healing, character creation) — the server uses it to detect when a "
"character goes down. Do NOT also put HP/TP in combat_stats, this is the only place for it."
),
},
"max_hp": {
"type": "integer",
"description": "Maximum hit points. Send together with current_hp.",
},
"combat_stats": {
"type": "object",
"description": (
"Key/value readouts EXCLUDING hit points (use current_hp/max_hp for those), e.g. "
"{\"RK\": \"19\", \"Initiative\": \"+1\", \"Tempo\": \"7,5 m\", \"Übungsbonus\": \"+2\"}. "
"Send the full current set each time — this replaces whatever was stored before."
),
},
"abilities": {
"type": "array",
"description": (
"Every notable class feature, racial trait, feat, or spell the character has — one "
"entry per ability. Each 'description' must be a clear, beginner-friendly explanation "
"of what it does and when/how to use it, not just its rules name. Send the full current "
"list each time — this replaces whatever was stored before."
),
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"description": {"type": "string"},
},
"required": ["name", "description"],
},
},
"equipment": {
"type": "array",
"description": "Full current equipment/inventory list, one item per string. Replaces whatever was stored before.",
"items": {"type": "string"},
},
"description": {
"type": "string",
"description": "Backstory/background narrative only — oaths, personality, motivation, current situation. Abilities and equipment go in their own fields, not here.",
},
},
"required": ["player_name"],
},
}
async def upsert(session: AsyncSession, game_id: uuid.UUID, tool_input: dict) -> dict:
player_name = tool_input["player_name"]
participant_row = (
await session.execute(
select(GameParticipant, User)
.join(User, User.id == GameParticipant.user_id)
.where(GameParticipant.game_id == game_id, User.name == player_name)
)
).first()
if participant_row is None:
raise ValueError(f"No participant named {player_name!r} found in this game")
participant, user = participant_row
character_id = tool_input.get("character_id")
character: Character | None = None
if character_id:
character = await session.get(Character, uuid.UUID(character_id))
if character is None or character.owner_id != user.id:
raise ValueError(f"Character {character_id!r} does not belong to {player_name!r}")
elif participant.character_id is not None:
# The player already has a character in this game (set by an earlier call in this
# session) — reuse it instead of creating a duplicate when the model omits character_id.
character = await session.get(Character, participant.character_id)
if character is None:
character = Character(owner_id=user.id, name=tool_input.get("name", "Unbenannt"), stats={})
session.add(character)
for field in ("name", "race", "char_class", "description"):
if field in tool_input and tool_input[field] is not None:
setattr(character, field, tool_input[field])
if "stats" in tool_input and tool_input["stats"] is not None:
character.stats = {**(character.stats or {}), **tool_input["stats"]}
if "combat_stats" in tool_input and tool_input["combat_stats"] is not None:
character.combat_stats = tool_input["combat_stats"]
if "current_hp" in tool_input and tool_input["current_hp"] is not None:
character.current_hp = tool_input["current_hp"]
if "max_hp" in tool_input and tool_input["max_hp"] is not None:
character.max_hp = tool_input["max_hp"]
if "abilities" in tool_input and tool_input["abilities"] is not None:
character.abilities = tool_input["abilities"]
if "equipment" in tool_input and tool_input["equipment"] is not None:
character.equipment = tool_input["equipment"]
await session.flush()
if participant.character_id != character.id:
participant.character_id = character.id
await session.commit()
await session.refresh(character)
return {
"character_id": str(character.id),
"name": character.name,
"current_hp": character.current_hp,
"max_hp": character.max_hp,
}