import { createHash } from 'node:crypto'; import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js'; import type { StoredStateFrame } from '../../../framework/state/index.js'; import { isClawclawRuntimeState } from '../../runtime-state.js'; import { projectAgentAbilities, type AgentAbilityState, } from '../../agent-ability-state.js'; type UnknownRecord = Record; export interface ClawclawDerivedEventRule { readonly id: string; readonly eventTypes: readonly string[]; readonly consumes?: readonly string[]; reset(): void; save?(): unknown; restore?(state: any): void; inspect(frame: StoredStateFrame>, events?: readonly RuntimeSourceEvent[]): RuntimeEventProposal[]; } function record(value: unknown): UnknownRecord | null { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as UnknownRecord : null; } function stableHash(value: unknown): string { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); } function occurredAt(frame: StoredStateFrame>): string { return new Date(frame.observedAtMs ?? frame.receivedAtMs).toISOString(); } function sourceIdentity(frame: StoredStateFrame>): number { return frame.epochSeq ?? frame.frameSeq; } function finiteNumber(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? value : undefined; } function roomSnapshot( frame: StoredStateFrame>, ): UnknownRecord | null | undefined { const state = frame.state; if (!isClawclawRuntimeState(state) || state.stage !== 'room') return undefined; return record(record(state.room)?.room); } function roomReadyPayload(room: UnknownRecord): UnknownRecord { const payload: UnknownRecord = { ready_to_start: true }; for (const key of [ 'room_code', 'room_type', 'status', 'is_owner', 'member_count', 'cooldown_seconds', ] as const) { if (room[key] !== undefined) payload[key] = room[key]; } if (payload.member_count === undefined && Array.isArray(room.members)) { payload.member_count = room.members.length; } return payload; } export class RoomReadyDerivedEventRule implements ClawclawDerivedEventRule { save() { return { ready: this.ready }; } restore(state: any) { this.ready = state?.ready === true; } readonly id = 'room-ready'; readonly eventTypes = ['room_ready_to_start'] as const; private ready = false; reset(): void { this.ready = false; } inspect(frame: StoredStateFrame>): RuntimeEventProposal[] { const room = roomSnapshot(frame); if (room === undefined) return []; const ready = room?.ready_to_start === true; const enteredReady = ready && !this.ready; this.ready = ready; if (!enteredReady || !room) return []; const payload = roomReadyPayload(room); return [{ type: 'room_ready_to_start', dedupeKey: `room-ready:${sourceIdentity(frame)}:${stableHash(payload)}`, dedupeScope: 'segment', payload, occurredAt: occurredAt(frame), }]; } } function meetingProjection(meeting: UnknownRecord): UnknownRecord { const projection: UnknownRecord = { caller: meeting.caller ?? null, sub_phase: meeting.sub_phase ?? null, first_speaker: meeting.first_speaker ?? null, current_speaker: meeting.current_speaker ?? null, }; for (const key of [ 'speech_order', 'speech_skipped', 'votes_submitted', 'alive_players', ] as const) { if (Array.isArray(meeting[key])) projection[key] = structuredClone(meeting[key]); } return projection; } function freshGameSnapshot( frame: StoredStateFrame>, ): UnknownRecord | null | undefined { const state = frame.state; if (!isClawclawRuntimeState(state)) return record(state); if ((state.game_snapshot.status !== 'fresh' && state.game_snapshot.status !== 'cached')) return undefined; return record(state.game_snapshot.state); } const EMERGENCY_WARNING_THRESHOLDS = [30, 20] as const; export class EmergencyCountdownDerivedEventRule implements ClawclawDerivedEventRule { save() { return { emergencyKey: this.emergencyKey, remainingSecs: this.remainingSecs, emittedThresholds: [...this.emittedThresholds] }; } restore(state: any) { if (!state) return; this.emergencyKey = state.emergencyKey; this.remainingSecs = state.remainingSecs; this.emittedThresholds.clear(); for (const value of state.emittedThresholds ?? []) this.emittedThresholds.add(value); } readonly id = 'emergency-countdown'; readonly eventTypes = ['emergency_countdown_warning'] as const; private emergencyKey = ''; private remainingSecs?: number; private readonly emittedThresholds = new Set(); reset(): void { this.emergencyKey = ''; this.remainingSecs = undefined; this.emittedThresholds.clear(); } inspect(frame: StoredStateFrame>): RuntimeEventProposal[] { const game = freshGameSnapshot(frame); if (game === undefined) return []; const emergency = record(game?.emergency); if (emergency?.active !== true) { this.reset(); return []; } const key = JSON.stringify([ emergency.task_name ?? null, emergency.room ?? null, finiteNumber(emergency.x) ?? null, finiteNumber(emergency.y) ?? null, ]); const remainingSecs = finiteNumber(emergency.remaining_secs); const sameEmergency = this.emergencyKey === key; let crossed: number[] = []; if (!sameEmergency) { this.emergencyKey = key; this.remainingSecs = undefined; this.emittedThresholds.clear(); if (remainingSecs !== undefined) { // A recovered Runtime may first observe an incident after one or more // thresholds. Wake only for the nearest still-relevant threshold. const nearest = [...EMERGENCY_WARNING_THRESHOLDS] .reverse() .find((threshold) => remainingSecs <= threshold); if (nearest !== undefined) crossed = [nearest]; } } else if (remainingSecs !== undefined && this.remainingSecs !== undefined) { crossed = EMERGENCY_WARNING_THRESHOLDS.filter((threshold) => ( this.remainingSecs! > threshold && remainingSecs <= threshold && !this.emittedThresholds.has(threshold) )); } this.remainingSecs = remainingSecs; for (const threshold of crossed) this.emittedThresholds.add(threshold); if (game?.you && record(game.you)?.is_alive === false) return []; return crossed.map((threshold) => { const payload: UnknownRecord = { threshold_secs: threshold, remaining_secs: remainingSecs, }; for (const field of ['task_name', 'room'] as const) { if (typeof emergency[field] === 'string') payload[field] = emergency[field]; } if (typeof game?.tick === 'number' || typeof game?.tick === 'string') payload.tick = game.tick; return { type: 'emergency_countdown_warning', dedupeKey: `emergency-countdown:${sourceIdentity(frame)}:${threshold}:${stableHash(key)}`, dedupeScope: 'segment' as const, payload, occurredAt: occurredAt(frame), }; }); } } export class AbilityStateDerivedEventRule implements ClawclawDerivedEventRule { save() { return { initialized: this.initialized, abilities: structuredClone(this.abilities) }; } restore(state: any) { if (!state) return; this.initialized = state.initialized; this.abilities = structuredClone(state.abilities); } readonly id = 'ability-state'; readonly eventTypes = [ 'ability.ready', 'ability.remaining_uses_changed', 'ability.exhausted', ] as const; private initialized = false; private abilities: AgentAbilityState[] = []; reset(): void { this.initialized = false; this.abilities = []; } inspect(frame: StoredStateFrame>): RuntimeEventProposal[] { const game = freshGameSnapshot(frame); if (game === undefined) return []; const current = projectAgentAbilities(game as Record) ?? []; if (!this.initialized) { this.initialized = true; this.abilities = structuredClone(current); return []; } const previousById = new Map(this.abilities.map((ability) => [ability.id, ability])); const proposals: RuntimeEventProposal[] = []; for (const ability of current) { const previous = previousById.get(ability.id); if (!previous) continue; const base: UnknownRecord = { ability_id: ability.id, ability_name: ability.name, }; if (typeof game?.tick === 'number' || typeof game?.tick === 'string') base.tick = game.tick; if (ability.effective_range_px !== undefined) { base.effective_range_px = ability.effective_range_px; } if (!previous.ready && ability.ready) { proposals.push({ type: 'ability.ready', dedupeKey: `ability-ready:${sourceIdentity(frame)}:${ability.id}`, dedupeScope: 'segment', payload: { ...base, remaining_uses: ability.remaining_uses }, occurredAt: occurredAt(frame), }); } if ( typeof previous.remaining_uses === 'number' && typeof ability.remaining_uses === 'number' && previous.remaining_uses !== ability.remaining_uses ) { const exhausted = ability.remaining_uses === 0; proposals.push({ type: exhausted ? 'ability.exhausted' : 'ability.remaining_uses_changed', dedupeKey: `ability-uses:${sourceIdentity(frame)}:${ability.id}:${ability.remaining_uses}`, dedupeScope: 'segment', payload: { ...base, previous_remaining_uses: previous.remaining_uses, remaining_uses: ability.remaining_uses, }, occurredAt: occurredAt(frame), }); } } this.abilities = structuredClone(current); return proposals; } } export class MeetingStateDerivedEventRule implements ClawclawDerivedEventRule { readonly id = 'meeting-state'; readonly eventTypes = ['meeting_state'] as const; private meetingActive = false; private round = 0; private lastProjection = ''; reset(): void { this.meetingActive = false; this.round = 0; this.lastProjection = ''; } inspect(frame: StoredStateFrame>): RuntimeEventProposal[] { const game = freshGameSnapshot(frame); if (game === undefined) return []; const meeting = record(game?.meeting); if (!meeting) { this.meetingActive = false; this.lastProjection = ''; return []; } if (!this.meetingActive) { this.round += 1; this.meetingActive = true; this.lastProjection = ''; } const projection = meetingProjection(meeting); const signature = JSON.stringify(projection); if (signature === this.lastProjection) return []; this.lastProjection = signature; const payload: UnknownRecord = { round: this.round, ...projection, }; if (typeof game?.tick === 'number' || typeof game?.tick === 'string') { payload.tick = game.tick; } return [{ type: 'meeting_state', dedupeKey: `meeting-state:${sourceIdentity(frame)}:${this.round}:${stableHash(projection)}`, dedupeScope: 'segment', payload, occurredAt: occurredAt(frame), }]; } }