const ACTION_FIELDS: Readonly> = Object.freeze({ move: ['action', 'target', 'target_x', 'target_y', 'stop_on_player', 'thinking_content'], kill: ['action', 'target_seat', 'thinking_content'], speech: ['action', 'text', 'thinking_content'], task: ['action', 'task_name', 'thinking_content'], report: ['action', 'thinking_content'], think: ['action', 'thinking_content'], }); const ERRORS: Readonly<{ unsupported: string; fieldDenied: string; invalid: string; move: string; target: string; speech: string; task: string; }> = Object.freeze({ unsupported: 'unsupported_behavior_action', fieldDenied: 'behavior_action_field_denied', invalid: 'invalid_behavior_action', move: 'invalid_behavior_move', target: 'invalid_behavior_target', speech: 'invalid_behavior_speech', task: 'invalid_behavior_task', }); function nonEmpty(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; } /** Credential-free Action whitelist for the unified Behavior Host. */ export function normalizeClawclawBehaviorActionPayload( value: unknown, ): Record { const errors = ERRORS; if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error(errors.invalid); } const record = value as Readonly>; const actionType = record.action; if (typeof actionType !== 'string' || !ACTION_FIELDS[actionType]) { throw new Error(errors.unsupported); } const allowed = new Set(ACTION_FIELDS[actionType]); if (Object.keys(record).some((key) => !allowed.has(key))) { throw new Error(errors.fieldDenied); } if (record.thinking_content !== undefined && typeof record.thinking_content !== 'string') { throw new Error(errors.invalid); } switch (actionType) { case 'move': { const room = nonEmpty(record.target); const coordinates = Number.isFinite(record.target_x) && Number.isFinite(record.target_y); if (room === coordinates) throw new Error(errors.move); if (record.stop_on_player !== undefined && typeof record.stop_on_player !== 'boolean') { throw new Error(errors.move); } break; } case 'kill': { const seat = record.target_seat; const validSeat = typeof seat === 'number' && Number.isInteger(seat) && seat >= 1 && seat <= 10; if (!validSeat) throw new Error(errors.target); break; } case 'speech': if (!nonEmpty(record.text)) throw new Error(errors.speech); break; case 'task': if (record.task_name !== undefined && !nonEmpty(record.task_name)) { throw new Error(errors.task); } break; } return Object.fromEntries(Object.entries(record).filter(([key]) => allowed.has(key))); }