import { loadClawclawMapAsset } from '../../../../lib/game-context.js'; import type { BehaviorPathQuery, Position, } from '../../../../sdk/behavior-plugin/index.js'; import { getLocalPathDistances } from '../../navigation/astar-path.js'; import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, } from '../../../framework/plugins/index.js'; import { isClawclawRuntimeState } from '../../runtime-state.js'; import { projectTaskChoices, projectTaskChoiceLocations } from '../../task-choice-projection.js'; import { CLAWCLAW_MAP_CAPABILITY, CLAWCLAW_PATH_DISTANCE_CAPABILITY, CLAWCLAW_TASKS_CAPABILITY, } from './context-capabilities.js'; export const CLAWCLAW_GAME_QUERY_PLUGIN_ID = 'clawclaw.game-query'; export interface ClawclawPathDistanceRequest { readonly queries: readonly Readonly[]; } export type ClawclawPathDistanceProvider = ( queries: readonly Readonly[], ) => readonly (number | null)[] | Promise; function finitePoint(value: Position): boolean { return Number.isFinite(value?.x) && Number.isFinite(value?.y); } function scopeKey(input: RuntimeEpochPluginInput>): string { return `${input.epoch.scope.sessionId}:${input.epoch.scope.segmentId}`; } function taskFaction(taskType: unknown): 'lobster' | 'crab' { return Number(taskType) === 1 ? 'crab' : 'lobster'; } function packagedMap(): Record { const asset = loadClawclawMapAsset(); return { rooms: (Array.isArray(asset?.rooms) ? asset.rooms : []).map((room: Record) => ({ name: room.name, polygon: structuredClone(room.polygon), })), all_task_locations: (Array.isArray(asset?.tasks) ? asset.tasks : []) .map((task: Record) => ({ name: task.name, room: task.room, x: task.x, y: task.y, faction: taskFaction(task.task_type), })), }; } const PACKAGED_MAP = packagedMap(); export function clawclawTasksFromGameState( gameState: Record | null | undefined, ): readonly Record[] | null { const tasks = gameState?.you?.tasks; return Array.isArray(tasks) ? structuredClone(projectTaskChoices(gameState, tasks)) : null; } function clawclawPlayersFromGameState( gameState: Record | null | undefined, ): readonly { name: string; seat: number }[] { const players = gameState?.players; if (!Array.isArray(players)) return []; return players.flatMap((player: Record) => { const name = typeof player?.name === 'string' ? player.name.trim() : ''; const seat = player?.seat; return name && Number.isInteger(seat) && seat >= 0 ? [{ name, seat }] : []; }); } export function clawclawMapFromGameState( gameState: Record | null | undefined, ): Record { const tasks = clawclawTasksFromGameState(gameState); return { ...structuredClone(PACKAGED_MAP), all_task_locations: structuredClone(projectTaskChoiceLocations(gameState, PACKAGED_MAP.all_task_locations)), all_players: clawclawPlayersFromGameState(gameState), ...(tasks === null ? {} : { your_tasks: tasks }), }; } /** Owns read-only game queries; consumers receive serializable values only. */ export class ClawclawGameQueryPlugin implements RuntimeEpochPlugin> { readonly kind = 'epoch' as const; readonly id = CLAWCLAW_GAME_QUERY_PLUGIN_ID; readonly version = '1'; readonly capabilities = { provides: [ CLAWCLAW_TASKS_CAPABILITY, CLAWCLAW_MAP_CAPABILITY, CLAWCLAW_PATH_DISTANCE_CAPABILITY, ], } as const; private unregister: Array<() => void> = []; private latestFreshGameState: Record | null = null; private latestFreshReceivedAt: string | null = null; private activeScopeKey: string | null = null; constructor( private readonly pathDistances: ClawclawPathDistanceProvider = getLocalPathDistances, ) {} private gameStateForQuery( queryContext: { readonly epochSeq?: number; readonly stateFrame?: Readonly<{ state: Record; receivedAtMs: number }>; }, ): { state: Record | null; receivedAt: string | null } { if (queryContext.epochSeq === undefined) { return { state: this.latestFreshGameState, receivedAt: this.latestFreshReceivedAt, }; } const snapshot = queryContext.stateFrame; if (!snapshot || !isClawclawRuntimeState(snapshot.state) || (snapshot.state.game_snapshot.status !== 'fresh' && snapshot.state.game_snapshot.status !== 'cached')) { return { state: null, receivedAt: null }; } return { state: snapshot.state.game_snapshot.state, receivedAt: new Date(snapshot.state.cycle?.stateReceivedAtMs ?? snapshot.receivedAtMs).toISOString(), }; } private currentTasks(gameState: Record | null): readonly Record[] | null { return clawclawTasksFromGameState(gameState); } private authoritativeTasks(gameState: Record | null): readonly Record[] { const tasks = this.currentTasks(gameState); if (tasks === null) throw new Error('authoritative_tasks_unavailable'); return tasks; } private receivedAt(value: string | null): string { return value ?? new Date().toISOString(); } start(context: RuntimeEpochPluginContext>): void { if (this.unregister.length > 0) { throw new Error('ClawClaw Game Query Plugin is already started.'); } this.unregister = [ context.capabilities.provideObservation({ capability: CLAWCLAW_TASKS_CAPABILITY, query: async (_request, scope, queryContext) => { const snapshot = this.gameStateForQuery(queryContext); return { scope, capability: CLAWCLAW_TASKS_CAPABILITY, receivedAt: this.receivedAt(snapshot.receivedAt), freshness: 'fresh', value: this.authoritativeTasks(snapshot.state), provenance: { source: 'epoch_game_state', projection: 'you.tasks', ...(queryContext.epochSeq === undefined ? {} : { epochSeq: queryContext.epochSeq }), }, }; }, }), context.capabilities.provideObservation({ capability: CLAWCLAW_MAP_CAPABILITY, query: async (_request, scope, queryContext) => { const snapshot = this.gameStateForQuery(queryContext); const tasks = this.currentTasks(snapshot.state); return { scope, capability: CLAWCLAW_MAP_CAPABILITY, receivedAt: this.receivedAt(snapshot.receivedAt), freshness: 'fresh', value: clawclawMapFromGameState(snapshot.state), provenance: { source: 'packaged_frontend_map_and_epoch_game_state', asset: 'src/assets/clawclaw-map.json', playersProjection: 'players', tasksProjection: tasks === null ? 'unavailable' : 'you.tasks', ...(queryContext.epochSeq === undefined ? {} : { epochSeq: queryContext.epochSeq }), }, }; }, }), context.capabilities.provideObservation< ClawclawPathDistanceRequest, readonly (number | null)[] >({ capability: CLAWCLAW_PATH_DISTANCE_CAPABILITY, query: async (request, scope) => { if (!Array.isArray(request?.queries) || request.queries.some(({ from, to }) => ( !finitePoint(from) || !finitePoint(to) ))) { throw new Error('invalid_path_distance_points'); } const provided = await this.pathDistances(request.queries); const value = Array.isArray(provided) ? [...provided] : []; if ( !Array.isArray(provided) || value.length !== request.queries.length || value.some(distance => distance !== null && !Number.isFinite(distance)) ) throw new Error('invalid_path_distance_result'); return { scope, capability: CLAWCLAW_PATH_DISTANCE_CAPABILITY, receivedAt: new Date().toISOString(), freshness: value.some(distance => distance === null) ? 'unknown' : 'fresh', value, provenance: { source: 'packaged_walkable_grid', algorithm: 'local_astar' }, }; }, }), ]; } update(input: RuntimeEpochPluginInput>): RuntimeEpochPluginResult { const nextScopeKey = scopeKey(input); if (nextScopeKey !== this.activeScopeKey) { this.activeScopeKey = nextScopeKey; this.latestFreshGameState = null; this.latestFreshReceivedAt = null; } const runtimeState = input.epoch.state; if (isClawclawRuntimeState(runtimeState) && (runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')) { this.latestFreshGameState = structuredClone(runtimeState.game_snapshot.state); this.latestFreshReceivedAt = new Date(runtimeState.cycle?.stateReceivedAtMs ?? input.frame.receivedAtMs).toISOString(); } return { outcome: 'noop', reason: 'query_provider' }; } stop(): void { for (const unregister of this.unregister.splice(0).reverse()) unregister(); this.latestFreshGameState = null; this.latestFreshReceivedAt = null; this.activeScopeKey = null; } }