Add player login, agent creation, and NPC chat
Browse filesBackend:
- database.py: users table with sha256+salt auth, session tokens
- routes.py: /auth/register, /auth/login, /auth/me, /auth/logout
+ /player/create, /player/update, /player/move, /player/plan, /player/talk
- Registration auto-creates player agent at town_square
- /player/talk feeds player message to NPC, returns LLM reply
Frontend:
- Login/register modal on page load (skip button for observers)
- Player panel in sidebar: location, move dropdown, Edit Profile, My Plans
- Agent profile editor modal (name, age, occupation, background, traits)
- Plans modal: view + add items to daily plan
- Talk button on NPC detail panel opens inline chat window
- Multi-turn chat: send message, NPC replies via LLM
- Gold ring drawn around player-controlled agent on map
- Session persisted in localStorage
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (3)
1 unmodified line234567899 unmodified lines192021222324176 unmodified lines2012022032042052061 unmodified linefrom __future__ import annotationsfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModelrouter = APIRouter()9 unmodified linesbackground: str = "A newcomer to Soci City."@router.get("/city")async def get_city():"""Get the full city state β locations, agents, time, weather."""176 unmodified lines}@router.post("/player/join")async def player_join(request: PlayerJoinRequest):"""Register a human player as a new agent in the simulation."""1 unmodified line23456789109 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485176 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115121 unmodified linefrom __future__ import annotationsfrom fastapi import APIRouter, HTTPException, Headerfrom pydantic import BaseModelfrom typing import Optionalrouter = APIRouter()9 unmodified linesbackground: str = "A newcomer to Soci City."# ββ Auth models βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass AuthRequest(BaseModel):username: strpassword: strclass PlayerCreateRequest(BaseModel):token: strname: strage: int = 30occupation: str = "Newcomer"background: str = "A newcomer to Soci City."extraversion: int = 5agreeableness: int = 7openness: int = 6class PlayerUpdateRequest(BaseModel):token: strname: Optional[str] = Noneage: Optional[int] = Noneoccupation: Optional[str] = Nonebackground: Optional[str] = Noneextraversion: Optional[int] = Noneagreeableness: Optional[int] = Noneopenness: Optional[int] = Noneclass PlayerTalkRequest(BaseModel):token: strtarget_id: strmessage: strclass PlayerMoveRequest(BaseModel):token: strlocation: strclass PlayerPlanRequest(BaseModel):token: strplan_item: str# ββ Helper ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def _get_player_from_token(token: str):"""Validate token and return (user, agent). Raises 401/404 on failure."""from soci.api.server import get_simulation, get_databasedb = get_database()sim = get_simulation()user = await db.get_user_by_token(token)if not user:raise HTTPException(status_code=401, detail="Invalid or expired session token")agent_id = user.get("agent_id")agent = sim.agents.get(agent_id) if agent_id else Nonereturn user, agent@router.get("/city")async def get_city():"""Get the full city state β locations, agents, time, weather."""176 unmodified lines}# ββ Auth endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@router.post("/auth/register")async def auth_register(request: AuthRequest):"""Register a new user and auto-create their player agent."""from soci.api.server import get_simulation, get_databasefrom soci.agents.agent import Agentfrom soci.agents.persona import Personadb = get_database()sim = get_simulation()if not request.username.strip():raise HTTPException(status_code=400, detail="Username cannot be empty")if len(request.password) < 3:raise HTTPException(status_code=400, detail="Password must be at least 3 characters")try:user = await db.create_user(request.username.strip(), request.password)except ValueError as e:raise HTTPException(status_code=409, detail=str(e))# Auto-create default player agent at town_squaresafe_name = request.username.strip()player_id = f"player_{safe_name.lower().replace(' ', '_')}"# Ensure unique IDsuffix = 1base_id = player_idwhile player_id in sim.agents:player_id = f"{base_id}_{suffix}"suffix += 1persona = Persona(id=player_id,name=safe_name,age=30,occupation="Newcomer",gender="unknown",background="A newcomer to Soci City.",home_location="town_square",work_location="",extraversion=5,agreeableness=7,openness=6,)agent = Agent(persona)agent.is_player = Truesim.add_agent(agent)await db.set_user_agent(safe_name, player_id)user["agent_id"] = player_idreturn user@router.post("/auth/login")async def auth_login(request: AuthRequest):"""Login and return session token."""from soci.api.server import get_databasedb = get_database()user = await db.authenticate_user(request.username.strip(), request.password)if not user:raise HTTPException(status_code=401, detail="Invalid username or password")return user@router.get("/auth/me")async def auth_me(authorization: str = Header(default="")):"""Verify session token and return current user info."""token = authorization.removeprefix("Bearer ").strip()if not token:raise HTTPException(status_code=401, detail="No token provided")from soci.api.server import get_databasedb = get_database()user = await db.get_user_by_token(token)if not user:raise HTTPException(status_code=401, detail="Invalid or expired token")return user@router.post("/auth/logout")async def auth_logout(authorization: str = Header(default="")):"""Invalidate session token."""token = authorization.removeprefix("Bearer ").strip()from soci.api.server import get_databasedb = get_database()await db.logout_user(token)return {"ok": True}# ββ Player management endpoints βββββββββββββββββββββββββββββββββββββββββββββββ@router.post("/player/create")async def player_create(request: PlayerCreateRequest):"""Create or replace the player's agent."""from soci.api.server import get_simulation, get_databasefrom soci.agents.agent import Agentfrom soci.agents.persona import Personadb = get_database()sim = get_simulation()user = await db.get_user_by_token(request.token)if not user:raise HTTPException(status_code=401, detail="Invalid token")player_id = f"player_{request.name.lower().replace(' ', '_')}"suffix = 1base_id = player_idwhile player_id in sim.agents and sim.agents[player_id].persona.name != request.name:player_id = f"{base_id}_{suffix}"suffix += 1# Remove old agent if existsold_id = user.get("agent_id")if old_id and old_id in sim.agents:loc = sim.city.get_location(sim.agents[old_id].location)if loc:loc.remove_agent(old_id)del sim.agents[old_id]persona = Persona(id=player_id,name=request.name,age=request.age,occupation=request.occupation,background=request.background,home_location="town_square",work_location="",extraversion=request.extraversion,agreeableness=request.agreeableness,openness=request.openness,)agent = Agent(persona)agent.is_player = Truesim.add_agent(agent)await db.set_user_agent(user["username"], player_id)return {"agent_id": player_id}@router.put("/player/update")async def player_update(request: PlayerUpdateRequest):"""Update the player's persona fields in-place."""user, agent = await _get_player_from_token(request.token)if not agent:raise HTTPException(status_code=404, detail="No player agent found")p = agent.personaif request.name is not None:p.name = request.nameagent.name = request.nameif request.age is not None:p.age = request.ageif request.occupation is not None:p.occupation = request.occupationif request.background is not None:p.background = request.backgroundif request.extraversion is not None:p.extraversion = max(1, min(10, request.extraversion))if request.agreeableness is not None:p.agreeableness = max(1, min(10, request.agreeableness))if request.openness is not None:p.openness = max(1, min(10, request.openness))return {"ok": True}@router.post("/player/move")async def player_move(request: PlayerMoveRequest):"""Move the player to a city location."""from soci.api.server import get_simulationfrom soci.agents.agent import AgentAction, AgentStatesim = get_simulation()user, agent = await _get_player_from_token(request.token)if not agent:raise HTTPException(status_code=404, detail="No player agent found")loc = sim.city.get_location(request.location)if not loc:raise HTTPException(status_code=400, detail=f"Unknown location: {request.location}")action = AgentAction(type="move", target=request.location, detail=f"Walking to {loc.name}", duration_ticks=1)await sim._execute_action(agent, action)return {"ok": True, "location": agent.location}@router.post("/player/talk")async def player_talk(request: PlayerTalkRequest):"""Send a message to an NPC and get their LLM-generated reply."""from soci.api.server import get_simulationfrom soci.actions.conversation import Conversation, ConversationTurn, continue_conversationimport uuidsim = get_simulation()user, player = await _get_player_from_token(request.token)if not player:raise HTTPException(status_code=404, detail="No player agent found")target = sim.agents.get(request.target_id)if not target:raise HTTPException(status_code=404, detail="Target agent not found")# Build a conversation with the player's message as the opening turnconv_id = f"player_conv_{uuid.uuid4().hex[:8]}"conv = Conversation(id=conv_id,location=player.location,participants=[player.id, target.id],topic="player interaction",max_turns=20,)player_turn = ConversationTurn(speaker_id=player.id,speaker_name=player.name,message=request.message,tick=sim.clock.total_ticks,)conv.add_turn(player_turn)# Let the NPC respond via LLMreply_turn = await continue_conversation(conv, target, player, sim.llm, sim.clock)# Update relationshiptarget.relationships.get_or_create(player.id, player.name)player.relationships.get_or_create(target.id, target.name)# Add memory to bothplayer.add_observation(tick=sim.clock.total_ticks, day=sim.clock.day, time_str=sim.clock.time_str,content=f"I said to {target.name}: \"{request.message}\"",importance=4, involved_agents=[target.id],)if reply_turn and reply_turn.speaker_id == target.id:target.add_observation(tick=sim.clock.total_ticks, day=sim.clock.day, time_str=sim.clock.time_str,content=f"{player.name} talked to me: \"{request.message}\"",importance=4, involved_agents=[player.id],)return {"reply": reply_turn.message, "inner_thought": reply_turn.inner_thought}return {"reply": "(no response)", "inner_thought": ""}@router.post("/player/plan")async def player_add_plan(request: PlayerPlanRequest):"""Append an item to the player's daily plan."""user, agent = await _get_player_from_token(request.token)if not agent:raise HTTPException(status_code=404, detail="No player agent found")agent.daily_plan.append(request.plan_item)return {"ok": True, "daily_plan": agent.daily_plan}# ββ Legacy join/action (kept for compatibility) βββββββββββββββββββββββββββββββ@router.post("/player/join")async def player_join(request: PlayerJoinRequest):"""Register a human player as a new agent in the simulation."""
1 unmodified line23456789101 unmodified line12131415161734 unmodified lines525354555657114 unmodified lines1721731741 unmodified linefrom __future__ import annotationsimport jsonimport loggingimport osfrom pathlib import Pathfrom typing import Optional1 unmodified linelogger = logging.getLogger(__name__)# SOCI_DATA_DIR env var lets you point at a persistent disk (e.g. /var/data on Render).DB_DIR = Path(os.environ.get("SOCI_DATA_DIR", "data"))DEFAULT_DB = DB_DIR / "soci.db"34 unmodified linesCREATE INDEX IF NOT EXISTS idx_event_tick ON event_log(tick);CREATE INDEX IF NOT EXISTS idx_event_agent ON event_log(agent_id);CREATE INDEX IF NOT EXISTS idx_conv_tick ON conversations(tick);"""114 unmodified lines}for r in rows]1 unmodified line234567891011121 unmodified line1415161718192021222334 unmodified lines58596061626364656667686970717273114 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532541 unmodified linefrom __future__ import annotationsimport hashlibimport jsonimport loggingimport osimport secretsfrom pathlib import Pathfrom typing import Optional1 unmodified linelogger = logging.getLogger(__name__)def _hash_password(password: str, salt: str) -> str:return hashlib.sha256(f"{salt}{password}".encode()).hexdigest()# SOCI_DATA_DIR env var lets you point at a persistent disk (e.g. /var/data on Render).DB_DIR = Path(os.environ.get("SOCI_DATA_DIR", "data"))DEFAULT_DB = DB_DIR / "soci.db"34 unmodified linesCREATE INDEX IF NOT EXISTS idx_event_tick ON event_log(tick);CREATE INDEX IF NOT EXISTS idx_event_agent ON event_log(agent_id);CREATE INDEX IF NOT EXISTS idx_conv_tick ON conversations(tick);CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT NOT NULL UNIQUE,password_hash TEXT NOT NULL,salt TEXT NOT NULL,token TEXT UNIQUE,agent_id TEXT,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);"""114 unmodified lines}for r in rows]# ββ Auth / user methods ββββββββββββββββββββββββββββββββββββββββββββββββββasync def create_user(self, username: str, password: str) -> dict:"""Create a new user. Raises ValueError if username taken."""assert self._db is not Nonesalt = secrets.token_hex(16)pw_hash = _hash_password(password, salt)token = secrets.token_hex(32)try:await self._db.execute("INSERT INTO users (username, password_hash, salt, token) VALUES (?, ?, ?, ?)",(username, pw_hash, salt, token),)await self._db.commit()except aiosqlite.IntegrityError:raise ValueError(f"Username '{username}' is already taken")return {"username": username, "token": token, "agent_id": None}async def authenticate_user(self, username: str, password: str) -> Optional[dict]:"""Verify credentials and return user dict with fresh token, or None."""assert self._db is not Nonecursor = await self._db.execute("SELECT username, password_hash, salt, agent_id FROM users WHERE username = ?",(username,),)row = await cursor.fetchone()if not row:return Nonestored_hash = row[1]salt = row[2]if _hash_password(password, salt) != stored_hash:return Nonetoken = secrets.token_hex(32)await self._db.execute("UPDATE users SET token = ? WHERE username = ?", (token, username))await self._db.commit()return {"username": row[0], "token": token, "agent_id": row[3]}async def get_user_by_token(self, token: str) -> Optional[dict]:"""Look up a user by their session token."""assert self._db is not Nonecursor = await self._db.execute("SELECT username, agent_id FROM users WHERE token = ?", (token,))row = await cursor.fetchone()if not row:return Nonereturn {"username": row[0], "agent_id": row[1]}async def set_user_agent(self, username: str, agent_id: str) -> None:"""Link a player agent to a user account."""assert self._db is not Noneawait self._db.execute("UPDATE users SET agent_id = ? WHERE username = ?", (agent_id, username))await self._db.commit()async def logout_user(self, token: str) -> None:"""Invalidate a session token."""assert self._db is not Noneawait self._db.execute("UPDATE users SET token = NULL WHERE token = ?", (token,))await self._db.commit()
157 unmodified lines15815916016116216345 unmodified lines2092102112122132144 unmodified lines2192202212222232241591 unmodified lines181618171818181918201821760 unmodified lines25822583258425852586258799 unmodified lines268726882689269026912692185 unmodified lines2878287928802881288228833 unmodified lines288728882889289028912892157 unmodified lines::-webkit-scrollbar { width: 6px; }::-webkit-scrollbar-track { background: #1a1a2e; }::-webkit-scrollbar-thumb { background: #0f3460; border-radius: 3px; }</style></head><body>45 unmodified lines<div class="sidebar-tab" data-tab="events" onclick="switchTab('events')">Events</div></div><div id="tab-agents" class="tab-content active"><div id="agent-detail"></div></div><div id="tab-conversations" class="tab-content">4 unmodified lines</div></div></div><script>// ============================================================// CONFIG1591 unmodified linesctx.scale(scale, scale);if (isSel) { ctx.shadowColor = color; ctx.shadowBlur = 14; }// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// SLEEPING VIEW β agent lying on a bed// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ760 unmodified lines<div class="section-header">Recent Memories</div>${memories.map(m=>`<div class="memory-item"><span class="memory-time">${m.time||''}</span> ${esc(m.content||'')}</div>`).join('')||'<div class="memory-item" style="color:#555">No memories yet</div>'}`;}99 unmodified linesdocument.getElementById('cost').textContent = $m ? `$${$m[1]}` : '$0.00';agents = data.agents || {};const tick = clock.total_ticks || 0;if (tick !== lastTick) fetchSecondaryData();185 unmodified lines}}// ============================================================// INIT// ============================================================3 unmodified linesfetchControls();connectWebSocket();setInterval(() => { if (!ws || ws.readyState !== WebSocket.OPEN) fetchState(); }, POLL_INTERVAL);</script></body></html>157 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323445 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013024 unmodified lines3073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693701591 unmodified lines19621963196419651966196719681969197019711972197319741975197619771978760 unmodified lines2739274027412742274327442745274627472748274999 unmodified lines2849285028512852285328542855185 unmodified lines30413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843 unmodified lines3288328932903291329232933294157 unmodified lines::-webkit-scrollbar { width: 6px; }::-webkit-scrollbar-track { background: #1a1a2e; }::-webkit-scrollbar-thumb { background: #0f3460; border-radius: 3px; }/* ββ Player / Auth UI ββββββββββββββββββββββββββββββββββββββββββββββ */.modal-overlay {position: fixed; inset: 0; background: rgba(0,0,0,0.72);display: flex; align-items: center; justify-content: center; z-index: 1000;}.modal-box {background: #0f1b35; border: 1px solid #1a3a6e; border-radius: 8px;padding: 24px 28px; min-width: 300px; max-width: 420px; width: 90%;color: #e0e0e0;}.modal-box h2 { color: #4ecca3; margin: 0 0 16px; font-size: 18px; }.modal-box label { display: block; font-size: 11px; color: #888; margin: 10px 0 3px; }.modal-box input, .modal-box textarea, .modal-box select {width: 100%; box-sizing: border-box; background: #0a1628; border: 1px solid #1a3a6e;color: #e0e0e0; padding: 7px 10px; border-radius: 4px; font-size: 13px;}.modal-box textarea { resize: vertical; min-height: 60px; font-family: inherit; }.modal-box input[type=range] { padding: 4px 0; border: none; background: none; }.modal-row { display: flex; gap: 10px; }.modal-row > * { flex: 1; }.modal-actions { display: flex; gap: 10px; margin-top: 18px; justify-content: flex-end; }.btn-primary {background: #4ecca3; color: #0a1628; border: none; padding: 8px 18px;border-radius: 4px; cursor: pointer; font-weight: 700; font-size: 13px;}.btn-primary:hover { background: #3ab88e; }.btn-secondary {background: transparent; color: #a0a0c0; border: 1px solid #1a3a6e;padding: 8px 18px; border-radius: 4px; cursor: pointer; font-size: 13px;}.btn-secondary:hover { color: #e0e0e0; border-color: #4ecca3; }.btn-danger {background: transparent; color: #e94560; border: 1px solid #e94560;padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 11px;}.auth-switch { text-align: center; margin-top: 12px; font-size: 12px; color: #666; }.auth-switch a { color: #4ecca3; cursor: pointer; text-decoration: underline; }.auth-error { color: #e94560; font-size: 12px; margin-top: 8px; }#player-panel {background: rgba(78,204,163,0.06); border: 1px solid rgba(78,204,163,0.2);border-radius: 6px; margin: 8px; padding: 10px 12px; display: none;}#player-panel .pp-header {display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;}#player-panel .pp-title { color: #4ecca3; font-size: 11px; font-weight: 700; letter-spacing: 1px; }#player-panel .pp-name { color: #e0e0e0; font-size: 13px; font-weight: 600; }#player-panel .pp-loc { color: #888; font-size: 10px; }.pp-actions { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }.pp-btn {background: #0f3460; color: #a0a0c0; border: 1px solid #1a3a6e;padding: 4px 10px; border-radius: 3px; cursor: pointer; font-size: 11px;}.pp-btn:hover { background: #1a4a80; color: #e0e0e0; }.pp-move { display: flex; gap: 4px; margin-top: 6px; align-items: center; }.pp-move select { flex: 1; background: #0a1628; color: #e0e0e0; border: 1px solid #1a3a6e; padding: 4px 6px; border-radius: 3px; font-size: 11px; }.pp-move button { background: #4ecca3; color: #0a1628; border: none; padding: 4px 10px; border-radius: 3px; cursor: pointer; font-size: 11px; font-weight: 700; }/* Chat panel */#chat-panel {border-top: 1px solid #1a3a6e; margin-top: 10px; padding-top: 10px; display: none;}#chat-panel .chat-header { color: #4ecca3; font-size: 11px; font-weight: 700; margin-bottom: 6px; display: flex; justify-content: space-between; }#chat-messages { max-height: 180px; overflow-y: auto; font-size: 12px; margin-bottom: 8px; }.chat-msg-you { color: #4ecca3; margin: 3px 0; }.chat-msg-npc { color: #e0e0e0; margin: 3px 0; }.chat-msg-thinking { color: #666; font-style: italic; margin: 3px 0; }#chat-input-row { display: flex; gap: 6px; }#chat-input { flex: 1; background: #0a1628; color: #e0e0e0; border: 1px solid #1a3a6e; padding: 6px 8px; border-radius: 3px; font-size: 12px; font-family: inherit; }#chat-send { background: #4ecca3; color: #0a1628; border: none; padding: 6px 12px; border-radius: 3px; cursor: pointer; font-weight: 700; font-size: 12px; }.slider-val { font-size: 12px; color: #4ecca3; min-width: 20px; text-align: right; }</style></head><body>45 unmodified lines<div class="sidebar-tab" data-tab="events" onclick="switchTab('events')">Events</div></div><div id="tab-agents" class="tab-content active"><!-- Player panel (shown when logged in) --><div id="player-panel"><div class="pp-header"><span class="pp-title">YOU</span><button class="btn-danger" onclick="authLogout()" style="padding:2px 8px;font-size:10px">Logout</button></div><div id="pp-name" class="pp-name">Loading...</div><div id="pp-loc" class="pp-loc"></div><div class="pp-move"><select id="pp-move-select"></select><button onclick="playerMove()">Go</button></div><div class="pp-actions"><button class="pp-btn" onclick="openProfileEditor()">Edit Profile</button><button class="pp-btn" onclick="openPlansModal()">My Plans</button></div></div><div id="agent-detail"></div></div><div id="tab-conversations" class="tab-content">4 unmodified lines</div></div></div><!-- Login / Register modal --><div id="login-modal" class="modal-overlay" style="display:none"><div class="modal-box"><h2 id="auth-title">Welcome to Soci City</h2><div id="auth-error" class="auth-error" style="display:none"></div><label>Username</label><input type="text" id="auth-username" placeholder="Your name" autocomplete="username"><label>Password</label><input type="password" id="auth-password" placeholder="Password" autocomplete="current-password"><div class="modal-actions"><button class="btn-secondary" onclick="closeLoginModal()">Skip</button><button class="btn-primary" id="auth-btn" onclick="authSubmit()">Login</button></div><div class="auth-switch" id="auth-switch-text">No account? <a onclick="toggleAuthMode()">Register</a></div></div></div><!-- Agent Profile Editor modal --><div id="profile-modal" class="modal-overlay" style="display:none"><div class="modal-box"><h2>Your Agent Profile</h2><div class="modal-row"><div><label>Name</label><input type="text" id="pe-name" placeholder="Your name"></div><div><label>Age</label><input type="number" id="pe-age" min="16" max="90" value="30"></div></div><label>Occupation</label><input type="text" id="pe-occupation" placeholder="e.g. Artist, Engineer, Chef"><label>Background (how you describe yourself)</label><textarea id="pe-background" rows="3" placeholder="A few sentences about yourself..."></textarea><label>Extraversion: <span id="pe-extra-val" class="slider-val">5</span></label><input type="range" id="pe-extraversion" min="1" max="10" value="5" oninput="document.getElementById('pe-extra-val').textContent=this.value"><label>Agreeableness: <span id="pe-agree-val" class="slider-val">7</span></label><input type="range" id="pe-agreeableness" min="1" max="10" value="7" oninput="document.getElementById('pe-agree-val').textContent=this.value"><label>Openness: <span id="pe-open-val" class="slider-val">6</span></label><input type="range" id="pe-openness" min="1" max="10" value="6" oninput="document.getElementById('pe-open-val').textContent=this.value"><div class="modal-actions"><button class="btn-secondary" onclick="document.getElementById('profile-modal').style.display='none'">Cancel</button><button class="btn-primary" onclick="saveProfile()">Save</button></div></div></div><!-- My Plans modal --><div id="plans-modal" class="modal-overlay" style="display:none"><div class="modal-box"><h2>My Plans</h2><div id="plans-list" style="font-size:12px;color:#a0a0c0;margin-bottom:12px;min-height:40px"></div><label>Add a plan</label><input type="text" id="plans-input" placeholder="e.g. Go to the cafe and meet someone" onkeydown="if(event.key==='Enter')addPlan()"><div class="modal-actions"><button class="btn-secondary" onclick="document.getElementById('plans-modal').style.display='none'">Close</button><button class="btn-primary" onclick="addPlan()">Add</button></div></div></div><script>// ============================================================// CONFIG1591 unmodified linesctx.scale(scale, scale);if (isSel) { ctx.shadowColor = color; ctx.shadowBlur = 14; }// Gold ring for player-controlled agentif (agent.is_player) {ctx.beginPath();ctx.arc(0, 0, 22, 0, Math.PI * 2);ctx.strokeStyle = '#f0c040';ctx.lineWidth = 2.5;ctx.globalAlpha = 0.8;ctx.stroke();ctx.globalAlpha = 1.0;}// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// SLEEPING VIEW β agent lying on a bed// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ760 unmodified lines<div class="section-header">Recent Memories</div>${memories.map(m=>`<div class="memory-item"><span class="memory-time">${m.time||''}</span> ${esc(m.content||'')}</div>`).join('')||'<div class="memory-item" style="color:#555">No memories yet</div>'}${playerToken && playerAgentId && data.id !== playerAgentId ? `<div style="margin-top:10px"><button class="btn-primary" style="width:100%" onclick="openChat('${data.id}')">Talk to ${esc(data.name||'them')}</button></div>` : ''}`;}99 unmodified linesdocument.getElementById('cost').textContent = $m ? `$${$m[1]}` : '$0.00';agents = data.agents || {};renderPlayerPanel();const tick = clock.total_ticks || 0;if (tick !== lastTick) fetchSecondaryData();185 unmodified lines}}// ============================================================// PLAYER / AUTH// ============================================================let playerToken = localStorage.getItem('soci_token') || null;let playerUsername = localStorage.getItem('soci_username') || null;let playerAgentId = localStorage.getItem('soci_agent_id') || null;let chatTargetId = null;let chatHistory = [];let authMode = 'login'; // 'login' or 'register'function closeLoginModal() {document.getElementById('login-modal').style.display = 'none';}function toggleAuthMode() {authMode = authMode === 'login' ? 'register' : 'login';document.getElementById('auth-title').textContent = authMode === 'login' ? 'Welcome to Soci City' : 'Create Account';document.getElementById('auth-btn').textContent = authMode === 'login' ? 'Login' : 'Register';document.getElementById('auth-switch-text').innerHTML = authMode === 'login'? 'No account? <a onclick="toggleAuthMode()">Register</a>': 'Have an account? <a onclick="toggleAuthMode()">Login</a>';document.getElementById('auth-error').style.display = 'none';}async function authSubmit() {const username = document.getElementById('auth-username').value.trim();const password = document.getElementById('auth-password').value;const errEl = document.getElementById('auth-error');if (!username || !password) { errEl.textContent = 'Please fill in both fields'; errEl.style.display = 'block'; return; }const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';try {const res = await fetch(window.location.origin + endpoint, {method: 'POST', headers: {'Content-Type':'application/json'},body: JSON.stringify({username, password})});const data = await res.json();if (!res.ok) { errEl.textContent = data.detail || 'Error'; errEl.style.display = 'block'; return; }playerToken = data.token;playerUsername = data.username;playerAgentId = data.agent_id || null;localStorage.setItem('soci_token', playerToken);localStorage.setItem('soci_username', playerUsername);if (playerAgentId) localStorage.setItem('soci_agent_id', playerAgentId);closeLoginModal();renderPlayerPanel();} catch(e) { errEl.textContent = 'Connection error'; errEl.style.display = 'block'; }}async function authLogout() {if (playerToken) {try { await fetch(window.location.origin + '/api/auth/logout', {method:'POST', headers:{'Authorization':'Bearer '+playerToken}}); } catch(e){}}playerToken = playerUsername = playerAgentId = null;localStorage.removeItem('soci_token'); localStorage.removeItem('soci_username'); localStorage.removeItem('soci_agent_id');document.getElementById('player-panel').style.display = 'none';document.getElementById('chat-panel') && (document.getElementById('chat-panel').style.display = 'none');}function renderPlayerPanel() {const panel = document.getElementById('player-panel');if (!playerToken) { panel.style.display = 'none'; return; }panel.style.display = 'block';const agent = playerAgentId ? agents[playerAgentId] : null;document.getElementById('pp-name').textContent = agent ? agent.name : (playerUsername || 'You');const locName = agent ? (locations[agent.location]?.name || agent.location || '') : '';document.getElementById('pp-loc').textContent = locName ? `@ ${locName}` : '';// Populate move dropdown from known locationsconst sel = document.getElementById('pp-move-select');const locKeys = Object.keys(locations);if (locKeys.length > 0) {sel.innerHTML = locKeys.map(lid => {const ln = locations[lid]?.name || lid;const selected = agent && agent.location === lid ? ' selected' : '';return `<option value="${lid}"${selected}>${ln}</option>`;}).join('');}}async function playerMove() {if (!playerToken || !playerAgentId) return;const location = document.getElementById('pp-move-select').value;try {const res = await fetch(window.location.origin + '/api/player/move', {method:'POST', headers:{'Content-Type':'application/json'},body: JSON.stringify({token: playerToken, location})});if (res.ok) renderPlayerPanel();} catch(e){}}function openProfileEditor() {if (!playerAgentId) return;const agent = agents[playerAgentId];if (agent) {document.getElementById('pe-name').value = agent.name || '';document.getElementById('pe-age').value = agent.age || 30;document.getElementById('pe-occupation').value = agent.occupation || '';}document.getElementById('profile-modal').style.display = 'flex';}async function saveProfile() {if (!playerToken) return;const body = {token: playerToken,name: document.getElementById('pe-name').value.trim(),age: parseInt(document.getElementById('pe-age').value)||30,occupation: document.getElementById('pe-occupation').value.trim(),background: document.getElementById('pe-background').value.trim(),extraversion: parseInt(document.getElementById('pe-extraversion').value),agreeableness: parseInt(document.getElementById('pe-agreeableness').value),openness: parseInt(document.getElementById('pe-openness').value),};try {const res = await fetch(window.location.origin + '/api/player/update', {method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)});if (res.ok) { document.getElementById('profile-modal').style.display='none'; renderPlayerPanel(); }} catch(e){}}function openPlansModal() {if (!playerAgentId) return;const agent = agents[playerAgentId];const plans = agent?.daily_plan || [];const listEl = document.getElementById('plans-list');listEl.innerHTML = plans.length > 0? plans.map((p,i) => `<div style="padding:3px 0;border-bottom:1px solid #1a3a6e">${i+1}. ${esc(p)}</div>`).join(''): '<div style="color:#555">No plans yet.</div>';document.getElementById('plans-modal').style.display = 'flex';}async function addPlan() {if (!playerToken) return;const input = document.getElementById('plans-input');const item = input.value.trim();if (!item) return;try {const res = await fetch(window.location.origin + '/api/player/plan', {method:'POST', headers:{'Content-Type':'application/json'},body: JSON.stringify({token: playerToken, plan_item: item})});if (res.ok) { input.value = ''; openPlansModal(); }} catch(e){}}// Chat with an NPCfunction openChat(targetId) {chatTargetId = targetId;chatHistory = [];const target = agents[targetId];let chatPanel = document.getElementById('chat-panel');if (!chatPanel) {chatPanel = document.createElement('div');chatPanel.id = 'chat-panel';document.getElementById('agent-detail').after(chatPanel);}chatPanel.style.display = 'block';chatPanel.innerHTML = `<div class="chat-header"><span>Talking to ${esc(target?.name || targetId)}</span><span style="cursor:pointer;color:#888" onclick="closeChat()">β Close</span></div><div id="chat-messages"></div><div id="chat-input-row"><input id="chat-input" type="text" placeholder="Say something..." onkeydown="if(event.key==='Enter')sendChat()"><button id="chat-send" onclick="sendChat()">Send</button></div>`;}function closeChat() {chatTargetId = null;const p = document.getElementById('chat-panel');if (p) p.style.display = 'none';}function appendChatMsg(cls, speaker, text) {const el = document.getElementById('chat-messages');if (!el) return;const div = document.createElement('div');div.className = cls;div.innerHTML = `<b>${esc(speaker)}:</b> ${esc(text)}`;el.appendChild(div);el.scrollTop = el.scrollHeight;}async function sendChat() {if (!playerToken || !playerAgentId || !chatTargetId) return;const input = document.getElementById('chat-input');const message = input.value.trim();if (!message) return;input.value = '';input.disabled = true;document.getElementById('chat-send').disabled = true;appendChatMsg('chat-msg-you', playerUsername || 'You', message);appendChatMsg('chat-msg-thinking', agents[chatTargetId]?.name || '...', '...');try {const res = await fetch(window.location.origin + '/api/player/talk', {method:'POST', headers:{'Content-Type':'application/json'},body: JSON.stringify({token: playerToken, target_id: chatTargetId, message})});const el = document.getElementById('chat-messages');if (el && el.lastChild) el.lastChild.remove(); // remove thinking...if (res.ok) {const data = await res.json();appendChatMsg('chat-msg-npc', agents[chatTargetId]?.name || chatTargetId, data.reply || '(no reply)');} else {appendChatMsg('chat-msg-thinking', 'System', 'Could not get a response right now.');}} catch(e) {const el = document.getElementById('chat-messages');if (el && el.lastChild) el.lastChild.remove();appendChatMsg('chat-msg-thinking', 'System', 'Connection error.');}input.disabled = false;document.getElementById('chat-send').disabled = false;input.focus();}async function checkSession() {if (!playerToken) { document.getElementById('login-modal').style.display = 'flex'; return; }try {const res = await fetch(window.location.origin + '/api/auth/me', {headers:{'Authorization':'Bearer '+playerToken}});if (res.ok) {const data = await res.json();playerUsername = data.username;playerAgentId = data.agent_id;if (playerAgentId) localStorage.setItem('soci_agent_id', playerAgentId);renderPlayerPanel();} else {// Token expiredplayerToken = null; localStorage.removeItem('soci_token');document.getElementById('login-modal').style.display = 'flex';}} catch(e) { renderPlayerPanel(); }}// ============================================================// INIT// ============================================================3 unmodified linesfetchControls();connectWebSocket();setInterval(() => { if (!ws || ws.readyState !== WebSocket.OPEN) fetchState(); }, POLL_INTERVAL);checkSession();</script></body></html>