import { isCurrentAgentRoomOwner, isRoomReadyToStart, memberCount, type RoomSnapshot, } from '../lib/room.js'; import { trainingRoleForCharacterId } from '../lib/training-role.js'; export interface ClawclawRoomStateProjectionOptions { receivedAt?: string; profileName?: string; terminalPhase?: string | null; } function ownMember(snapshot: RoomSnapshot | null | undefined): Record | undefined { if (!snapshot || !Array.isArray(snapshot.members)) return undefined; const seat = snapshot.my_seat ?? snapshot.seat; return snapshot.members.find((member) => seat !== undefined && member?.seat === seat); } /** Project the backend room protocol into the canonical Agent/Runtime State. */ export function projectClawclawRoomState( snapshot: RoomSnapshot | null | undefined, options: ClawclawRoomStateProjectionOptions = {}, ): Record { const room = snapshot ?? null; const me = ownMember(room); const roleLockCharacterId = me?.agent_id && room?.role_config ? room.role_config[me.agent_id] : undefined; const roleLock = trainingRoleForCharacterId(roleLockCharacterId); const phase = options.terminalPhase ?? (room?.status === 'starting' ? 'room_starting' : room?.status === 'playing' ? 'room_playing' : 'room_waiting'); return { ...(options.receivedAt ? { ts: options.receivedAt } : {}), phase, you: { name: options.profileName || me?.name, seat: room?.my_seat ?? room?.seat, is_owner: isCurrentAgentRoomOwner(room), }, room: room ? { ...room, member_count: memberCount(room), is_owner: isCurrentAgentRoomOwner(room), ready_to_start: isRoomReadyToStart(room), ...(roleLockCharacterId !== undefined ? { role_lock_character_id: roleLockCharacterId } : {}), ...(roleLock !== undefined ? { role_lock: roleLock } : {}), } : null, }; }