export const GAME_SYNC_PROTOCOL_VERSION = 1 as const; export interface GameSyncSnapshotData { readonly seq: number; readonly game_id: string; readonly tick: number; readonly locale: 'zh-CN' | 'en-US'; readonly state: Record; readonly events: readonly Record[]; } export interface GameSyncUpdateData { readonly seq: number; readonly game_id: string; readonly tick: number; readonly state_delta: Record; readonly events: readonly Record[]; } export interface GameSyncResumeData { readonly status: 'complete'; readonly from_seq?: number | null; readonly to_seq: number; readonly replayed_count: number; readonly tick: number; } export interface GameSyncErrorData { readonly code: string; readonly recoverable: boolean; readonly message?: string; } export type GameSyncPerceptionTime = | { readonly source_tick: number; readonly from_source_tick?: never; readonly to_source_tick?: never } | { readonly source_tick?: never; readonly from_source_tick: number; readonly to_source_tick: number }; export type GameSyncPerceptionReport = GameSyncPerceptionTime & { readonly id: string; readonly perceiver_id?: string; readonly name: string; readonly output: string; }; export interface GameSyncResourceInfo { readonly id: string; readonly name: string; readonly description?: string; } export interface GameSyncRuntimeReport { readonly perceivers?: readonly GameSyncResourceInfo[] | null; readonly strategies?: readonly GameSyncResourceInfo[] | null; } export interface GameSyncRuntimeReportMessage { readonly type: 'game.sync.runtime.report'; readonly data: GameSyncRuntimeReport; } export interface GameSyncPerceptionReportMessage { readonly type: 'game.sync.perception.report'; readonly data: { readonly perceptions: readonly GameSyncPerceptionReport[]; }; } export type GameSyncServerMessage = | { readonly type: 'game.sync.snapshot'; readonly data: GameSyncSnapshotData } | { readonly type: 'game.sync.update'; readonly data: GameSyncUpdateData } | { readonly type: 'game.sync.resume'; readonly data: GameSyncResumeData } | { readonly type: 'game.sync.error'; readonly data: GameSyncErrorData }; function record(value: unknown, field: string): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError(`${field} must be an object`); } return value as Record; } function integer(value: unknown, field: string, minimum = 0): number { if (!Number.isInteger(value) || Number(value) < minimum) { throw new TypeError(`${field} must be an integer >= ${minimum}`); } return Number(value); } function nonEmptyString(value: unknown, field: string): string { if (typeof value !== 'string' || value.length === 0) { throw new TypeError(`${field} must be a non-empty string`); } return value; } function eventArray(value: unknown, field: string): Record[] { if (!Array.isArray(value)) { throw new TypeError(`${field} must be an array`); } return value.map((event, index) => { const parsed = structuredClone(record(event, `${field}[${index}]`)); nonEmptyString(parsed.event_id, `${field}[${index}].event_id`); nonEmptyString(parsed.type, `${field}[${index}].type`); integer(parsed.tick, `${field}[${index}].tick`); return parsed; }); } const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; function resourceId(value: unknown, field: string): string { const id = nonEmptyString(value, field).trim(); if (!id || [...id].length > 128) throw new TypeError(`${field} must contain 1 to 128 characters`); return id; } export function gameSyncRuntimeReportMessage(report: GameSyncRuntimeReport): GameSyncRuntimeReportMessage { if (report.perceivers == null && report.strategies == null) { throw new TypeError('GameSync runtime report requires perceivers or strategies'); } const data: { perceivers?: GameSyncResourceInfo[] | null; strategies?: GameSyncResourceInfo[] | null } = {}; for (const key of ['perceivers', 'strategies'] as const) { const list = report[key]; if (list === undefined) continue; if (list === null) { data[key] = null; continue; } if (!Array.isArray(list) || list.length > 50) throw new TypeError(`${key} must contain at most 50 resources`); const ids = new Set(); data[key] = list.map(item => { const id = resourceId(item.id, `${key}.id`); if (ids.has(id)) throw new TypeError(`${key} resource IDs must be unique`); ids.add(id); const name = nonEmptyString(item.name, `${key}.name`).trim(); if (!name) throw new TypeError(`${key}.name must not be blank`); if (item.description !== undefined && typeof item.description !== 'string') throw new TypeError(`${key}.description must be a string`); return { id, name, description: item.description?.trim() ?? '' }; }); } return { type: 'game.sync.runtime.report', data }; } /** Build one client perception report frame using the backend's all-or-nothing validation rules. */ export function gameSyncPerceptionReportMessage( perceptions: readonly GameSyncPerceptionReport[], ): GameSyncPerceptionReportMessage { if (perceptions.length < 1 || perceptions.length > 20) { throw new TypeError('GameSync perception report must contain between 1 and 20 items'); } const ids = new Set(); const detached = perceptions.map((perception, index) => { if (!UUID_PATTERN.test(perception.id)) { throw new TypeError(`GameSync perception report[${index}].id must be a UUID`); } if (ids.has(perception.id)) { throw new TypeError('GameSync perception report IDs must be unique within a batch'); } ids.add(perception.id); if (typeof perception.name !== 'string' || perception.name.length === 0) { throw new TypeError(`GameSync perception report[${index}].name must be a non-empty string`); } if (typeof perception.output !== 'string') { throw new TypeError(`GameSync perception report[${index}].output must be a string`); } const instant = perception.source_tick !== undefined; const interval = perception.from_source_tick !== undefined || perception.to_source_tick !== undefined; if (instant === interval) throw new TypeError('Perception report requires exactly one instantaneous or interval time'); if (instant) integer(perception.source_tick, `GameSync perception report[${index}].source_tick`); else { integer(perception.from_source_tick, `GameSync perception report[${index}].from_source_tick`); integer(perception.to_source_tick, `GameSync perception report[${index}].to_source_tick`); if (perception.from_source_tick! > perception.to_source_tick!) throw new TypeError('Perception report time interval is reversed'); } return { ...perception, ...(perception.perceiver_id === undefined ? {} : { perceiver_id: resourceId(perception.perceiver_id, `GameSync perception report[${index}].perceiver_id`), }) }; }); return { type: 'game.sync.perception.report', data: { perceptions: detached }, }; } /** Validate only the envelope and sequencing fields CCL must trust. */ export function parseGameSyncMessage(value: unknown): GameSyncServerMessage { const envelope = record(value, 'GameSync message'); const type = nonEmptyString(envelope.type, 'GameSync message.type'); const data = record(envelope.data, 'GameSync message.data'); if (type === 'game.sync.snapshot') { const locale = data.locale; if (locale !== 'zh-CN' && locale !== 'en-US') { throw new TypeError('game.sync.snapshot.data.locale is invalid'); } return { type, data: { seq: integer(data.seq, 'game.sync.snapshot.data.seq', 1), game_id: nonEmptyString(data.game_id, 'game.sync.snapshot.data.game_id'), tick: integer(data.tick, 'game.sync.snapshot.data.tick'), locale, state: structuredClone(record(data.state, 'game.sync.snapshot.data.state')), // Older v2 instances did not emit this field. Treat absence as an // empty history so a rolling backend update cannot break CCL startup. events: eventArray(data.events ?? [], 'game.sync.snapshot.data.events'), }, }; } if (type === 'game.sync.update') { const events = eventArray(data.events, 'game.sync.update.data.events'); return { type, data: { seq: integer(data.seq, 'game.sync.update.data.seq', 1), game_id: nonEmptyString(data.game_id, 'game.sync.update.data.game_id'), tick: integer(data.tick, 'game.sync.update.data.tick'), state_delta: structuredClone(record(data.state_delta, 'game.sync.update.data.state_delta')), events, }, }; } if (type === 'game.sync.resume') { if (data.status !== 'complete') throw new TypeError('game.sync.resume.data.status is invalid'); const fromSeq = data.from_seq == null ? data.from_seq : integer(data.from_seq, 'game.sync.resume.data.from_seq', 1); const toSeq = integer(data.to_seq, 'game.sync.resume.data.to_seq', 1); const replayedCount = integer( data.replayed_count, 'game.sync.resume.data.replayed_count', ); if (fromSeq == null && replayedCount !== 0) { throw new TypeError( 'game.sync.resume.data.from_seq must be present when replayed_count is non-zero', ); } if (fromSeq != null) { if (replayedCount === 0) { throw new TypeError( 'game.sync.resume.data.from_seq must be null when replayed_count is zero', ); } if (toSeq < fromSeq || replayedCount !== toSeq - fromSeq + 1) { throw new TypeError('game.sync.resume.data replay range is inconsistent'); } } return { type, data: { status: 'complete', ...(fromSeq === undefined ? {} : { from_seq: fromSeq }), to_seq: toSeq, replayed_count: replayedCount, tick: integer(data.tick, 'game.sync.resume.data.tick'), }, }; } if (type === 'game.sync.error') { if (typeof data.recoverable !== 'boolean') { throw new TypeError('game.sync.error.data.recoverable must be a boolean'); } return { type, data: { code: nonEmptyString(data.code, 'game.sync.error.data.code'), recoverable: data.recoverable, ...(typeof data.message === 'string' ? { message: data.message } : {}), }, }; } throw new TypeError(`unsupported GameSync message type '${type}'`); } function mergeObject(previous: Record, delta: Record): Record { const result = structuredClone(previous); for (const [key, value] of Object.entries(delta)) { const old = result[key]; result[key] = old && value && typeof old === 'object' && typeof value === 'object' && !Array.isArray(old) && !Array.isArray(value) ? mergeObject(old, value) : structuredClone(value); } return result; } function mergePlayers(previous: unknown, delta: unknown): unknown[] { const prior = Array.isArray(previous) ? structuredClone(previous) : []; if (!Array.isArray(delta)) throw new TypeError('GameSync state_delta.players must be an array'); const bySeat = new Map>(); for (const player of prior) { const value = record(player, 'GameSync players entry'); if (Number.isInteger(value.seat)) bySeat.set(Number(value.seat), value); } for (const player of delta) { const value = record(player, 'GameSync state_delta.players entry'); const seat = integer(value.seat, 'GameSync state_delta.players.seat'); bySeat.set(seat, mergeObject(bySeat.get(seat) ?? {}, value)); } return [...bySeat.values()].sort((left, right) => Number(left.seat) - Number(right.seat)); } function semanticActive(previous: unknown, delta: unknown, field: string): Record { const value = record(delta, `GameSync state_delta.${field}`); if (value.active === false) return { active: false }; return mergeObject( previous && typeof previous === 'object' && !Array.isArray(previous) ? previous as Record : {}, value, ); } /** Apply the exact field semantics documented by GameSync v2. */ export function applyGameSyncDelta( previous: Readonly>, stateDelta: Readonly>, ): Record { const next: Record = structuredClone(previous) as Record; for (const [field, rawValue] of Object.entries(stateDelta)) { if (field === 'players') { next.players = mergePlayers(next.players, rawValue); continue; } if (field === 'visible_players' || field === 'visible_corpses') { if (!Array.isArray(rawValue)) throw new TypeError(`GameSync state_delta.${field} must be an array`); next[field] = structuredClone(rawValue); continue; } if (field === 'you') { const delta = record(rawValue, 'GameSync state_delta.you'); next.you = mergeObject(record(next.you ?? {}, 'GameSync state.you'), delta); if (delta.activity?.kind === 'idle') next.you.activity = { kind: 'idle' }; continue; } if (field === 'meeting') { const delta = record(rawValue, 'GameSync state_delta.meeting'); next.meeting = semanticActive(next.meeting, delta, field); if (delta.active !== false) { for (const replace of ['speech_order', 'speeches', 'speech_skipped', 'votes_submitted']) { if (Object.hasOwn(delta, replace)) next.meeting[replace] = structuredClone(delta[replace]); } } continue; } if (field === 'emergency' || field === 'octopus_time') { next[field] = semanticActive(next[field], rawValue, field); continue; } if (field === 'crab_sabotage') { const delta = record(rawValue, 'GameSync state_delta.crab_sabotage'); next.crab_sabotage = mergeObject( record(next.crab_sabotage ?? {}, 'GameSync state.crab_sabotage'), delta, ); if (typeof delta.status === 'string' && !delta.status.startsWith('cooldown_')) { delete next.crab_sabotage.cooldown_remaining_secs; } continue; } next[field] = structuredClone(rawValue); } return next; } export function gameSyncUrl(baseUrl: string, resumeSeq?: number): string { const url = new URL(baseUrl); url.searchParams.set('protocol_version', String(GAME_SYNC_PROTOCOL_VERSION)); if (resumeSeq !== undefined) url.searchParams.set('resume_seq', String(resumeSeq)); else url.searchParams.delete('resume_seq'); return url.toString(); }