Skip to main content

manabrew_agent_interface/agent_impl/
mod.rs

1use std::collections::HashMap;
2
3use forge_foundation::{ManaAtom, ZoneType};
4use manabrew_engine::agent::notification::GameNotification;
5use manabrew_engine::agent::{
6    BinaryChoiceKind, CombatCostAction, GameEntity, ManaCostAction, PlayerAgent,
7    PriorityActionSpace, RollSwapChoice, TargetChoice,
8};
9use manabrew_engine::card::CounterType;
10use manabrew_engine::combat::DefenderId;
11use manabrew_engine::game::GameState;
12use manabrew_engine::ids::{CardId, PlayerId};
13use manabrew_engine::mana::ManaPool;
14use manabrew_engine::player::actions::player_action::AbilityRef;
15use manabrew_engine::player::actions::PlayerAction as EnginePlayerAction;
16
17use crate::game_log_event::GameLogEntryDto;
18use crate::game_snapshot_event::GameSnapshotEventDto;
19use crate::game_view_dto::{card_to_dto, CardDto, GameViewDto, GameViewDtoExt, StepKind};
20use crate::ids_codec::{card_id_str, parse_card_id, parse_player_id, player_id_str};
21use crate::mana_action_id::{mana_ability_actions, parse_tap_action_id};
22use crate::prompt::*;
23
24mod choices;
25mod combat;
26mod costs;
27mod library;
28mod targeting;
29
30/// Match a mana symbol letter (e.g. "U") or a full color name (e.g. "Blue")
31/// against a list of color strings.  Handles the Blue/U mismatch where the
32/// mana symbol "U" doesn't match the first character of "Blue".
33pub(crate) fn find_matching_color<'a>(
34    pending: &str,
35    colors: impl Iterator<Item = &'a String>,
36) -> Option<String> {
37    let mana_to_name: &[(&str, &str)] = &[
38        ("W", "White"),
39        ("U", "Blue"),
40        ("B", "Black"),
41        ("R", "Red"),
42        ("G", "Green"),
43        ("C", "Colorless"),
44    ];
45    colors
46        .into_iter()
47        .find(|c| {
48            // Direct case-insensitive match (covers both "U"=="U" and "Blue"=="Blue")
49            c.eq_ignore_ascii_case(pending)
50            // Mana symbol → full name lookup (covers "U" matching "Blue")
51            || mana_to_name.iter().any(|(sym, name)| {
52                pending.eq_ignore_ascii_case(sym) && c.eq_ignore_ascii_case(name)
53            })
54            // Full name → mana symbol lookup (covers "Blue" matching "U")
55            || mana_to_name.iter().any(|(sym, name)| {
56                pending.eq_ignore_ascii_case(name) && c.eq_ignore_ascii_case(sym)
57            })
58        })
59        .cloned()
60}
61
62pub(crate) fn parse_express_mana_choice(color: Option<&str>) -> Option<u16> {
63    color
64        .map(|color| ManaAtom::from_name(&color.to_ascii_lowercase()))
65        .filter(|&atom| atom != 0)
66}
67
68/// Answers the prompts a `PromptAgent` builds.
69///
70pub trait Responder {
71    fn respond(&mut self, prompt: AgentPrompt) -> ClientToServerMessage;
72    fn present(&mut self, _message: &AgentMessage) {}
73    fn await_ack(&mut self) -> ClientToServerMessage {
74        ClientToServerMessage::Response {
75            prompt_id: 0,
76            action: PromptOutput::DiceRolled(DiceRolledOutput::DiceRolledAcknowledged),
77        }
78    }
79    fn send_log(&mut self, _entry: GameLogEntryDto) {}
80    fn send_snapshot(&mut self, _snapshot: GameSnapshotEventDto) {}
81}
82
83pub struct PromptAgent<R: Responder> {
84    pub player_id: PlayerId,
85    pub game_id: String,
86    pub responder: R,
87    pending_prompt: Option<AgentPrompt>,
88    pub(crate) latest_view: Option<GameViewDto>,
89    source_cards: HashMap<CardId, CardDto>,
90    pub(crate) pending_restore_checkpoint: Option<u64>,
91    pub pass_until: Option<manabrew_engine::agent::PassUntilTarget>,
92    conceded: bool,
93    next_prompt_id: u32,
94    pub(crate) targeting_cancellable: bool,
95    pub(crate) targeting_cancelled: bool,
96}
97
98impl<R: Responder> PromptAgent<R> {
99    pub fn new(player_id: PlayerId, game_id: String, responder: R) -> Self {
100        Self {
101            player_id,
102            game_id,
103            responder,
104            pending_prompt: None,
105            latest_view: None,
106            source_cards: HashMap::new(),
107            pending_restore_checkpoint: None,
108            pass_until: None,
109            conceded: false,
110            next_prompt_id: 0,
111            targeting_cancellable: false,
112            targeting_cancelled: false,
113        }
114    }
115
116    fn build_prompt(&mut self, inner: PromptInput, source: Option<CardId>) -> AgentPrompt {
117        self.next_prompt_id += 1;
118        let source_card = source.and_then(|card_id| self.source_cards.get(&card_id).cloned());
119        let source_ability_text = source_card.as_ref().and_then(|card| {
120            self.latest_view
121                .as_ref()?
122                .stack
123                .iter()
124                .rev()
125                .find(|entry| entry.source_id == card.id)?
126                .source_ability_text
127                .clone()
128        });
129        AgentPrompt {
130            prompt_id: self.next_prompt_id,
131            deciding_player_id: player_id_str(self.player_id),
132            source_card,
133            source_ability_text,
134            input: inner,
135        }
136    }
137
138    pub(crate) fn send_prompt(&mut self, inner: PromptInput, source: Option<CardId>) {
139        let prompt = self.build_prompt(inner, source);
140        self.emit_state();
141        self.responder
142            .present(&AgentMessage::Prompt(prompt.clone()));
143        self.pending_prompt = Some(prompt);
144    }
145
146    pub(crate) fn recv_action(&mut self) -> PromptOutput {
147        let prompt = self
148            .pending_prompt
149            .take()
150            .expect("recv_action called without a pending prompt");
151        if self.conceded {
152            return Self::default_pass();
153        }
154        loop {
155            match self.responder.respond(prompt.clone()) {
156                ClientToServerMessage::Response { prompt_id: 0, .. } => {
157                    return Self::default_pass();
158                }
159                ClientToServerMessage::Response { prompt_id, action } => {
160                    if prompt_id != prompt.prompt_id {
161                        self.reject(
162                            &prompt,
163                            ProtocolErrorCode::StalePrompt,
164                            format!(
165                                "response for prompt {prompt_id}, open prompt is {}",
166                                prompt.prompt_id
167                            ),
168                        );
169                        continue;
170                    }
171                    match prompt.input.validate_response(&action) {
172                        Ok(()) => return action,
173                        Err(ResponseViolation::WrongPromptType) => {
174                            self.reject(
175                                &prompt,
176                                ProtocolErrorCode::WrongPromptType,
177                                "response output does not match the prompt type".to_string(),
178                            );
179                        }
180                        Err(ResponseViolation::UnknownActionId(id)) => {
181                            self.reject(
182                                &prompt,
183                                ProtocolErrorCode::UnknownActionId,
184                                format!("action id {id:?} was not advertised by the prompt"),
185                            );
186                        }
187                        Err(ResponseViolation::CancelNotAllowed) => {
188                            self.reject(
189                                &prompt,
190                                ProtocolErrorCode::CancelNotAllowed,
191                                "this prompt is not cancellable".to_string(),
192                            );
193                        }
194                    }
195                }
196                ClientToServerMessage::Directive { directive } => {
197                    self.handle_directive(directive);
198                    return Self::default_pass();
199                }
200            }
201        }
202    }
203
204    fn default_pass() -> PromptOutput {
205        PromptOutput::ChooseAction(ChooseActionOutput::Pass {
206            until: None,
207            exhaust_stack: false,
208        })
209    }
210
211    fn reject(&mut self, prompt: &AgentPrompt, code: ProtocolErrorCode, message: String) {
212        self.responder.present(&AgentMessage::Error(ProtocolError {
213            code,
214            message,
215            prompt_id: Some(prompt.prompt_id),
216        }));
217        self.responder
218            .present(&AgentMessage::Prompt(prompt.clone()));
219    }
220
221    fn handle_directive(&mut self, directive: DirectiveInput) {
222        match directive {
223            DirectiveInput::Concede => self.conceded = true,
224        }
225    }
226
227    pub(crate) fn present_prompt(&mut self, inner: PromptInput, source: Option<CardId>) {
228        let prompt = self.build_prompt(inner, source);
229        self.emit_state();
230        self.responder.present(&AgentMessage::Prompt(prompt));
231    }
232
233    pub(crate) fn emit_state(&mut self) {
234        let game_view = self.view();
235        self.responder
236            .present(&AgentMessage::State(StateUpdate { game_view }));
237    }
238
239    pub(crate) fn emit_display(&mut self, event: DisplayEvent) {
240        self.responder.present(&AgentMessage::Display(event));
241    }
242
243    pub(crate) fn view(&self) -> GameViewDto {
244        self.latest_view.clone().unwrap_or_else(|| GameViewDto {
245            game_id: self.game_id.clone(),
246            step: StepKind::Main1,
247            ..Default::default()
248        })
249    }
250
251    pub(crate) fn card_ids(cards: &[CardId]) -> Vec<String> {
252        cards.iter().map(|&c| card_id_str(c)).collect()
253    }
254
255    pub(crate) fn player_ids(players: &[PlayerId]) -> Vec<String> {
256        players.iter().map(|&p| player_id_str(p)).collect()
257    }
258
259    pub(crate) fn attack_targets_to_dtos(
260        defenders: &[DefenderId],
261    ) -> Vec<crate::prompt::AttackTargetDto> {
262        use crate::prompt::AttackTargetKind;
263        defenders
264            .iter()
265            .map(|d| match d {
266                DefenderId::Player(pid) => crate::prompt::AttackTargetDto {
267                    id: format!("player-{}", pid.0),
268                    label: format!("Player {}", pid.0),
269                    kind: AttackTargetKind::Player,
270                },
271                // The Rust engine can't distinguish a planeswalker from a
272                // battle yet; approximate any permanent target as a walker.
273                DefenderId::Permanent(cid) => crate::prompt::AttackTargetDto {
274                    id: format!("card-{}", cid.0),
275                    label: format!("Permanent {}", cid.0),
276                    kind: AttackTargetKind::Planeswalker,
277                },
278            })
279            .collect()
280    }
281
282    fn alt_cost_kind(alt: manabrew_engine::spellability::AlternativeCost) -> AlternativeCostKind {
283        use manabrew_engine::spellability::AlternativeCost as A;
284        match alt {
285            A::Flashback => AlternativeCostKind::Flashback,
286            A::Spectacle => AlternativeCostKind::Spectacle,
287            A::Evoke => AlternativeCostKind::Evoke,
288            A::Dash => AlternativeCostKind::Dash,
289            A::Blitz => AlternativeCostKind::Blitz,
290            A::Escape => AlternativeCostKind::Escape,
291            A::Overload => AlternativeCostKind::Overload,
292            A::Madness => AlternativeCostKind::Madness,
293            A::Foretell => AlternativeCostKind::Foretell,
294            A::Emerge => AlternativeCostKind::Emerge,
295            A::Suspend => AlternativeCostKind::Suspend,
296            A::Morph => AlternativeCostKind::Morph,
297            A::Megamorph => AlternativeCostKind::Megamorph,
298            A::Bestow => AlternativeCostKind::Bestow,
299            A::Warp => AlternativeCostKind::Warp,
300            A::SacrificeAlt => AlternativeCostKind::SacrificeAlt,
301            A::Plot => AlternativeCostKind::Plot,
302            A::Awaken => AlternativeCostKind::Awaken,
303            A::Disturb => AlternativeCostKind::Disturb,
304            A::Harmonize => AlternativeCostKind::Harmonize,
305            A::Freerunning => AlternativeCostKind::Freerunning,
306            A::Impending => AlternativeCostKind::Impending,
307            A::Mayhem => AlternativeCostKind::Mayhem,
308            A::MTMtE => AlternativeCostKind::MTMtE,
309            A::Mutate => AlternativeCostKind::Mutate,
310            A::Prowl => AlternativeCostKind::Prowl,
311            A::Sneak => AlternativeCostKind::Sneak,
312            A::Surge => AlternativeCostKind::Surge,
313            A::WebSlinging => AlternativeCostKind::WebSlinging,
314            A::Plotted => AlternativeCostKind::Plotted,
315        }
316    }
317
318    fn play_mode_dto(mode: &manabrew_engine::agent::PlayCardMode) -> (PlayCardMode, String) {
319        use manabrew_engine::agent::PlayCardMode as E;
320        match mode {
321            E::Normal => (PlayCardMode::Normal, "Cast normally".to_string()),
322            E::BackFaceLand => (
323                PlayCardMode::BackFaceLand,
324                "Play back face as land".to_string(),
325            ),
326            E::RoomRightSplit => (PlayCardMode::RoomRightSplit, "Cast right room".to_string()),
327            E::StaticAlternative => (
328                PlayCardMode::StaticAlternative,
329                "Cast with alternative cost".to_string(),
330            ),
331            E::ForetellExile => (
332                PlayCardMode::ForetellExile,
333                "Foretell (exile face-down)".to_string(),
334            ),
335            E::UnlockDoor => (PlayCardMode::UnlockDoor, "Unlock door".to_string()),
336            E::Alternative(alt) => (
337                PlayCardMode::Alternative {
338                    cost: Self::alt_cost_kind(*alt),
339                },
340                format!("Cast with {alt:?}"),
341            ),
342        }
343    }
344
345    fn play_mode_key(mode: &manabrew_engine::agent::PlayCardMode) -> String {
346        use manabrew_engine::agent::PlayCardMode as E;
347        match mode {
348            E::Normal => "normal".to_string(),
349            E::BackFaceLand => "backFaceLand".to_string(),
350            E::RoomRightSplit => "roomRightSplit".to_string(),
351            E::StaticAlternative => "staticAlternative".to_string(),
352            E::ForetellExile => "foretellExile".to_string(),
353            E::UnlockDoor => "unlockDoor".to_string(),
354            E::Alternative(alt) => format!("alternative:{}", format!("{alt:?}").to_lowercase()),
355        }
356    }
357
358    fn parse_play_mode(mode_str: &str) -> Option<manabrew_engine::agent::PlayCardMode> {
359        use manabrew_engine::agent::PlayCardMode;
360        use manabrew_engine::spellability::AlternativeCost as A;
361        match mode_str {
362            "normal" => Some(PlayCardMode::Normal),
363            "backFaceLand" => Some(PlayCardMode::BackFaceLand),
364            "staticAlternative" => Some(PlayCardMode::StaticAlternative),
365            "foretellExile" => Some(PlayCardMode::ForetellExile),
366            "unlockDoor" => Some(PlayCardMode::UnlockDoor),
367            "roomRightSplit" => Some(PlayCardMode::RoomRightSplit),
368            s if s.starts_with("alternative:") => {
369                let alt = match &s["alternative:".len()..] {
370                    "flashback" => A::Flashback,
371                    "spectacle" => A::Spectacle,
372                    "evoke" => A::Evoke,
373                    "dash" => A::Dash,
374                    "blitz" => A::Blitz,
375                    "escape" => A::Escape,
376                    "overload" => A::Overload,
377                    "madness" => A::Madness,
378                    "foretell" => A::Foretell,
379                    "emerge" => A::Emerge,
380                    "suspend" => A::Suspend,
381                    "morph" => A::Morph,
382                    "megamorph" => A::Megamorph,
383                    "bestow" => A::Bestow,
384                    "warp" => A::Warp,
385                    "sacrificealt" => A::SacrificeAlt,
386                    "plot" => A::Plot,
387                    "awaken" => A::Awaken,
388                    "disturb" => A::Disturb,
389                    "harmonize" => A::Harmonize,
390                    "freerunning" => A::Freerunning,
391                    "impending" => A::Impending,
392                    "mayhem" => A::Mayhem,
393                    "mtmte" => A::MTMtE,
394                    "mutate" => A::Mutate,
395                    "prowl" => A::Prowl,
396                    "sneak" => A::Sneak,
397                    "surge" => A::Surge,
398                    "webslinging" => A::WebSlinging,
399                    "plotted" => A::Plotted,
400                    _ => return None,
401                };
402                Some(PlayCardMode::Alternative(alt))
403            }
404            _ => None,
405        }
406    }
407
408    pub(crate) fn parse_defender_id(id: &str, possible: &[DefenderId]) -> Option<DefenderId> {
409        if let Some(rest) = id.strip_prefix("player-") {
410            let idx: u32 = rest.parse().ok()?;
411            possible
412                .iter()
413                .find(|d| matches!(d, DefenderId::Player(p) if p.0 == idx))
414                .copied()
415        } else if let Some(rest) = id.strip_prefix("card-") {
416            let idx: u32 = rest.parse().ok()?;
417            possible
418                .iter()
419                .find(|d| matches!(d, DefenderId::Permanent(c) if c.0 == idx))
420                .copied()
421        } else {
422            None
423        }
424    }
425
426    pub(crate) fn recv_card_choice_or_first(&mut self, valid: &[CardId]) -> Option<CardId> {
427        match self.recv_action() {
428            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::Cancel) => {
429                self.targeting_cancelled = true;
430                None
431            }
432            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::BoardTargets { chosen }) => {
433                chosen.into_iter().find_map(|r| match r.kind {
434                    TargetKind::Card => parse_card_id(&r.id),
435                    _ => None,
436                })
437            }
438            _ => valid.first().copied(),
439        }
440    }
441
442    pub(crate) fn recv_player_choice_or_first(&mut self, valid: &[PlayerId]) -> Option<PlayerId> {
443        match self.recv_action() {
444            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::Cancel) => {
445                self.targeting_cancelled = true;
446                None
447            }
448            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::BoardTargets { chosen }) => {
449                chosen.into_iter().find_map(|r| match r.kind {
450                    TargetKind::Player => parse_player_id(&r.id),
451                    _ => None,
452                })
453            }
454            _ => valid.first().copied(),
455        }
456    }
457
458    pub(crate) fn recv_spell_choice_or_first(&mut self, valid: &[u32]) -> Option<u32> {
459        match self.recv_action() {
460            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::Cancel) => {
461                self.targeting_cancelled = true;
462                None
463            }
464            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::BoardTargets { chosen }) => {
465                chosen.into_iter().find_map(|r| match r.kind {
466                    TargetKind::Spell => crate::ids_codec::parse_stack_id(&r.id),
467                    _ => None,
468                })
469            }
470            _ => valid.first().copied(),
471        }
472    }
473}
474
475impl<R: Responder> PlayerAgent for PromptAgent<R> {
476    fn choose_targets_for(
477        &mut self,
478        sa: &mut manabrew_engine::spellability::SpellAbility,
479        game: &GameState,
480        mana_pools: &[ManaPool],
481    ) -> bool {
482        self.targeting_cancelled = false;
483        let ok = manabrew_engine::spellability::choose_targets_by_kind(self, sa, game, mana_pools);
484        ok && !self.targeting_cancelled
485    }
486
487    fn set_targeting_cancellable(&mut self, cancellable: bool) {
488        self.targeting_cancellable = cancellable;
489    }
490
491    fn get_pass_until(&self) -> Option<manabrew_engine::agent::PassUntilTarget> {
492        self.pass_until
493    }
494
495    fn clear_pass_until(&mut self) {
496        self.pass_until = None;
497    }
498
499    fn snapshot_state(&mut self, game: &GameState, mana_pools: &[ManaPool]) {
500        self.source_cards = game
501            .cards
502            .iter()
503            .map(|card| (card.id, card_to_dto(game, card.id)))
504            .collect();
505        self.latest_view = Some(GameViewDto::from_engine(
506            game,
507            mana_pools,
508            self.player_id,
509            &self.game_id,
510        ));
511    }
512
513    fn mulligan_decision(
514        &mut self,
515        player: PlayerId,
516        hand: &[CardId],
517        mulligan_count: u32,
518    ) -> bool {
519        choices::mulligan_decision(self, player, hand, mulligan_count)
520    }
521
522    fn mulligan_decision_send(&mut self, player: PlayerId, hand: &[CardId], mulligan_count: u32) {
523        choices::mulligan_decision_send(self, player, hand, mulligan_count);
524    }
525
526    fn mulligan_decision_recv(
527        &mut self,
528        player: PlayerId,
529        hand: &[CardId],
530        mulligan_count: u32,
531    ) -> bool {
532        choices::mulligan_decision_recv(self, player, hand, mulligan_count)
533    }
534
535    fn choose_cards_to_bottom(
536        &mut self,
537        player: PlayerId,
538        hand: &[CardId],
539        count: usize,
540    ) -> Vec<CardId> {
541        choices::choose_cards_to_bottom(self, player, hand, count)
542    }
543
544    fn choose_cards_to_bottom_send(&mut self, player: PlayerId, hand: &[CardId], count: usize) {
545        choices::choose_cards_to_bottom_send(self, player, hand, count);
546    }
547
548    fn choose_cards_to_bottom_recv(
549        &mut self,
550        player: PlayerId,
551        hand: &[CardId],
552        count: usize,
553    ) -> Vec<CardId> {
554        choices::choose_cards_to_bottom_recv(self, player, hand, count)
555    }
556
557    fn choose_action(
558        &mut self,
559        _player: PlayerId,
560        action_space: Option<&PriorityActionSpace>,
561        request_action_space: &mut dyn FnMut() -> PriorityActionSpace,
562    ) -> EnginePlayerAction {
563        if self.conceded {
564            return EnginePlayerAction::Concede;
565        }
566        let requested_action_space;
567        let action_space = match action_space {
568            Some(action_space) => action_space,
569            None => {
570                requested_action_space = request_action_space();
571                &requested_action_space
572            }
573        };
574        let playable = &action_space.playable;
575        let untappable_lands = &action_space.untappable_lands;
576        let _activatable = &action_space.activatable;
577        let untappable_land_ids: Vec<String> =
578            untappable_lands.iter().map(|&c| card_id_str(c)).collect();
579
580        let mut actions: Vec<AvailableAction> = Vec::new();
581        for play in playable.iter() {
582            let card_id = card_id_str(play.card_id);
583            let (mode, label) = Self::play_mode_dto(&play.mode);
584            let key = Self::play_mode_key(&play.mode);
585            actions.push(AvailableAction {
586                id: format!("cast:{card_id}:{key}"),
587                kind: AvailableActionKind::Cast {
588                    card_id: card_id.clone(),
589                    mode,
590                    label,
591                },
592            });
593        }
594        for a in action_space
595            .activatable
596            .iter()
597            .chain(action_space.mana_abilities.iter())
598        {
599            let card_id = card_id_str(a.card_id);
600            if a.is_mana_ability {
601                actions.extend(
602                    mana_ability_actions(
603                        &card_id,
604                        a.ability_index,
605                        &a.description,
606                        a.cost.clone(),
607                        a.produced_mana.clone(),
608                        a.produced_mana_amount,
609                    )
610                    .into_iter()
611                    .map(|(id, info)| AvailableAction {
612                        id,
613                        kind: AvailableActionKind::ActivateAbility(info),
614                    }),
615                );
616            } else {
617                actions.push(AvailableAction {
618                    id: format!("ability:{card_id}:{}", a.ability_index),
619                    kind: AvailableActionKind::ActivateAbility(ActivatableAbilityInfo {
620                        card_id,
621                        ability_index: a.ability_index,
622                        description: a.description.clone(),
623                        cost: a.cost.clone(),
624                        is_mana_ability: false,
625                        is_class_level_up: Some(a.is_class_level_up),
626                        produced_mana: None,
627                    }),
628                });
629            }
630        }
631        for card_id in &untappable_land_ids {
632            actions.push(AvailableAction {
633                id: format!("untap:{card_id}"),
634                kind: AvailableActionKind::UndoMana {
635                    card_id: card_id.clone(),
636                },
637            });
638        }
639
640        self.send_prompt(
641            PromptInput::ChooseAction(
642                manabrew_protocol::prompts::choose_action::ChooseActionInput { actions },
643            ),
644            None,
645        );
646        let prompt = self
647            .pending_prompt
648            .take()
649            .expect("choose_action called without a pending prompt");
650        let action = match self.responder.respond(prompt) {
651            ClientToServerMessage::Response { action, .. } => action,
652            ClientToServerMessage::Directive {
653                directive: DirectiveInput::Concede,
654            } => return EnginePlayerAction::Concede,
655        };
656        match action {
657            PromptOutput::ChooseAction(ChooseActionOutput::Act { action_id }) => {
658                if let Some(rest) = action_id.strip_prefix("cast:") {
659                    let (id_part, mode) = rest.split_once(':').unwrap_or((rest, "normal"));
660                    let resolved = parse_card_id(id_part).and_then(|cid| {
661                        Self::parse_play_mode(mode)
662                            .and_then(|m| {
663                                playable
664                                    .iter()
665                                    .copied()
666                                    .find(|play| play.card_id == cid && play.mode == m)
667                            })
668                            .or_else(|| playable.iter().copied().find(|play| play.card_id == cid))
669                    });
670                    resolved
671                        .map(EnginePlayerAction::CastSpell)
672                        .unwrap_or(EnginePlayerAction::PassPriority)
673                } else if let Some(rest) = action_id.strip_prefix("tap:") {
674                    let tap = parse_tap_action_id(rest);
675                    match parse_card_id(tap.card_id) {
676                        Some(cid) => EnginePlayerAction::ActivateMana(
677                            cid,
678                            tap.ability_index,
679                            parse_express_mana_choice(tap.color),
680                        ),
681                        None => EnginePlayerAction::PassPriority,
682                    }
683                } else if let Some(rest) = action_id.strip_prefix("ability:") {
684                    let (id_part, idx) = rest.split_once(':').unwrap_or((rest, ""));
685                    match (parse_card_id(id_part), idx.parse::<usize>()) {
686                        (Some(cid), Ok(ability_index)) => {
687                            EnginePlayerAction::ActivateAbility(AbilityRef {
688                                card_id: cid,
689                                ability_index,
690                            })
691                        }
692                        _ => EnginePlayerAction::PassPriority,
693                    }
694                } else if let Some(id_part) = action_id.strip_prefix("untap:") {
695                    parse_card_id(id_part)
696                        .map(EnginePlayerAction::UndoMana)
697                        .unwrap_or(EnginePlayerAction::PassPriority)
698                } else {
699                    EnginePlayerAction::PassPriority
700                }
701            }
702            PromptOutput::ChooseAction(ChooseActionOutput::Pass { until, .. }) => {
703                self.pass_until = until.and_then(|u| {
704                    Some(manabrew_engine::agent::PassUntilTarget {
705                        player: crate::ids_codec::parse_player_id(&u.player_id)?,
706                        phase: crate::game_view_dto::step_to_phase(u.phase),
707                        through_combat: u.through_combat,
708                    })
709                });
710                EnginePlayerAction::PassPriority
711            }
712            PromptOutput::ChooseAction(ChooseActionOutput::RestoreSnapshot { checkpoint_id }) => {
713                self.pending_restore_checkpoint = Some(checkpoint_id);
714                EnginePlayerAction::PassPriority
715            }
716            _ => EnginePlayerAction::PassPriority,
717        }
718    }
719
720    fn choose_attackers(
721        &mut self,
722        player: PlayerId,
723        available: &[CardId],
724        possible_defenders: &[DefenderId],
725    ) -> Vec<(CardId, DefenderId)> {
726        combat::choose_attackers(self, player, available, possible_defenders)
727    }
728
729    fn choose_blockers(
730        &mut self,
731        player: PlayerId,
732        attackers: &[CardId],
733        available_blockers: &[CardId],
734        max_blockers: Option<usize>,
735    ) -> Vec<(CardId, CardId)> {
736        combat::choose_blockers(self, player, attackers, available_blockers, max_blockers)
737    }
738
739    fn choose_damage_assignment_order(
740        &mut self,
741        player: PlayerId,
742        attacker: CardId,
743        blockers: &[CardId],
744    ) -> Vec<CardId> {
745        combat::choose_damage_assignment_order(self, player, attacker, blockers)
746    }
747
748    fn assign_combat_damage(
749        &mut self,
750        game: &GameState,
751        player: PlayerId,
752        attacker: CardId,
753        blockers_in_order: &[CardId],
754        defender_id: Option<DefenderId>,
755        damage_to_assign: i32,
756    ) -> Vec<(Option<CardId>, i32)> {
757        let attacker_has_deathtouch = game.card(attacker).has_deathtouch();
758        combat::choose_combat_damage_assignment(
759            self,
760            player,
761            attacker,
762            blockers_in_order,
763            defender_id,
764            damage_to_assign,
765            attacker_has_deathtouch,
766        )
767    }
768
769    fn choose_target_player(
770        &mut self,
771        player: PlayerId,
772        valid: &[PlayerId],
773        sa: Option<&manabrew_engine::spellability::SpellAbility>,
774    ) -> Option<PlayerId> {
775        let source = sa.and_then(|s| s.source);
776        let intent = sa
777            .map(crate::game_view_dto::targeting_intent_of)
778            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
779        let hostile = crate::game_view_dto::intent_is_hostile(intent);
780        targeting::choose_target_player(self, player, valid, source, hostile, intent)
781    }
782
783    fn choose_target_card(
784        &mut self,
785        player: PlayerId,
786        valid: &[CardId],
787        sa: Option<&manabrew_engine::spellability::SpellAbility>,
788    ) -> Option<CardId> {
789        let source = sa.and_then(|s| s.source);
790        let intent = sa
791            .map(crate::game_view_dto::targeting_intent_of)
792            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
793        let hostile = crate::game_view_dto::intent_is_hostile(intent);
794        targeting::choose_target_card(self, player, valid, source, hostile, intent)
795    }
796
797    fn choose_target_card_from_zone(
798        &mut self,
799        player: PlayerId,
800        zone: ZoneType,
801        valid: &[CardId],
802        sa: Option<&manabrew_engine::spellability::SpellAbility>,
803    ) -> Option<CardId> {
804        let source = sa.and_then(|s| s.source);
805        let intent = sa
806            .map(crate::game_view_dto::targeting_intent_of)
807            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
808        let hostile = crate::game_view_dto::intent_is_hostile(intent);
809        targeting::choose_target_card_from_zone(self, player, zone, valid, source, hostile, intent)
810    }
811
812    fn choose_target_any(
813        &mut self,
814        player: PlayerId,
815        valid_players: &[PlayerId],
816        valid_cards: &[CardId],
817        sa: Option<&manabrew_engine::spellability::SpellAbility>,
818    ) -> TargetChoice {
819        let source = sa.and_then(|s| s.source);
820        let intent = sa
821            .map(crate::game_view_dto::targeting_intent_of)
822            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
823        let hostile = crate::game_view_dto::intent_is_hostile(intent);
824        targeting::choose_target_any(
825            self,
826            player,
827            valid_players,
828            valid_cards,
829            source,
830            hostile,
831            intent,
832        )
833    }
834
835    fn choose_sacrifice(
836        &mut self,
837        player: PlayerId,
838        valid: &[CardId],
839        source: Option<CardId>,
840    ) -> Option<CardId> {
841        targeting::choose_sacrifice(self, player, valid, source)
842    }
843
844    fn reveal_cards(
845        &mut self,
846        game: &GameState,
847        _player: PlayerId,
848        cards: &[CardId],
849        zone: ZoneType,
850        owner: PlayerId,
851        message_prefix: Option<&str>,
852    ) {
853        choices::reveal_cards(self, game, cards, zone, owner, message_prefix)
854    }
855
856    fn choose_scry(
857        &mut self,
858        game: &GameState,
859        player: PlayerId,
860        source: Option<CardId>,
861        cards: &[CardId],
862    ) -> Vec<Vec<CardId>> {
863        library::choose_scry(self, game, player, source, cards)
864    }
865
866    fn choose_surveil(
867        &mut self,
868        game: &GameState,
869        player: PlayerId,
870        source: Option<CardId>,
871        cards: &[CardId],
872    ) -> Vec<Vec<CardId>> {
873        library::choose_surveil(self, game, player, source, cards)
874    }
875
876    fn choose_dig(
877        &mut self,
878        game: &GameState,
879        player: PlayerId,
880        valid: &[CardId],
881        max: usize,
882        optional: bool,
883    ) -> Vec<CardId> {
884        library::choose_dig(self, game, player, valid, max, optional)
885    }
886
887    fn choose_discard(&mut self, player: PlayerId, hand: &[CardId], num: usize) -> Vec<CardId> {
888        choices::choose_discard(self, player, hand, num)
889    }
890
891    fn choose_discard_any_number(
892        &mut self,
893        player: PlayerId,
894        hand: &[CardId],
895        min: usize,
896        max: usize,
897    ) -> Vec<CardId> {
898        choices::choose_discard_any_number(self, player, hand, min, max)
899    }
900
901    fn choose_legend_keep(&mut self, player: PlayerId, duplicates: &[CardId]) -> CardId {
902        choices::choose_legend_keep(self, player, duplicates)
903    }
904
905    fn choose_target_spell(
906        &mut self,
907        player: PlayerId,
908        valid: &[u32],
909        source: Option<CardId>,
910    ) -> Option<u32> {
911        targeting::choose_target_spell(self, player, valid, source)
912    }
913
914    fn choose_mode(
915        &mut self,
916        player: PlayerId,
917        descriptions: &[String],
918        min: usize,
919        max: usize,
920        source_card_id: Option<CardId>,
921    ) -> Vec<usize> {
922        choices::choose_mode(self, player, descriptions, min, max, source_card_id)
923    }
924
925    fn choose_spell_abilities_for_effect(
926        &mut self,
927        player: PlayerId,
928        abilities: &[manabrew_engine::spellability::SpellAbility],
929        num: usize,
930    ) -> Vec<usize> {
931        choices::choose_spell_abilities_for_effect(self, player, abilities, num)
932    }
933
934    fn get_ability_to_play(
935        &mut self,
936        player: PlayerId,
937        abilities: &[manabrew_engine::spellability::SpellAbility],
938    ) -> Option<usize> {
939        choices::get_ability_to_play(self, player, abilities)
940    }
941
942    fn choose_single_entity_for_effect(
943        &mut self,
944        player: PlayerId,
945        valid: &[GameEntity],
946        is_optional: bool,
947    ) -> Option<GameEntity> {
948        choices::choose_single_entity_for_effect(self, player, valid, is_optional)
949    }
950
951    fn choose_entities_for_effect(
952        &mut self,
953        player: PlayerId,
954        candidates: &[GameEntity],
955        min: usize,
956        max: usize,
957    ) -> Vec<GameEntity> {
958        choices::choose_entities_for_effect(self, player, candidates, min, max)
959    }
960
961    fn choose_single_replacement_effect(
962        &mut self,
963        player: PlayerId,
964        descriptions: &[String],
965    ) -> usize {
966        choices::choose_single_replacement_effect(self, player, descriptions)
967    }
968
969    fn confirm_replacement_effect(
970        &mut self,
971        player: PlayerId,
972        question: &str,
973        effect_description: &str,
974        source: Option<CardId>,
975    ) -> bool {
976        choices::confirm_replacement_effect(self, player, question, effect_description, source)
977    }
978
979    fn choose_optional_trigger(
980        &mut self,
981        player: PlayerId,
982        description: &str,
983        source: Option<CardId>,
984        api: Option<manabrew_engine::ability::api_type::ApiType>,
985    ) -> bool {
986        choices::choose_optional_trigger(self, player, description, source, api)
987    }
988
989    fn confirm_action(
990        &mut self,
991        player: PlayerId,
992        mode: Option<&str>,
993        message: &str,
994        options: &[String],
995        source: Option<CardId>,
996        api: Option<manabrew_engine::ability::api_type::ApiType>,
997    ) -> bool {
998        choices::confirm_action(self, player, mode, message, options, source, api)
999    }
1000
1001    fn confirm_payment(
1002        &mut self,
1003        player: PlayerId,
1004        cost_kind: &str,
1005        message: &str,
1006        source: Option<CardId>,
1007        api: Option<manabrew_engine::ability::api_type::ApiType>,
1008    ) -> bool {
1009        choices::confirm_payment(self, player, cost_kind, message, source, api)
1010    }
1011
1012    fn pay_cost_to_prevent_effect(
1013        &mut self,
1014        player: PlayerId,
1015        cost_kind: &str,
1016        message: &str,
1017        source: Option<CardId>,
1018        api: Option<manabrew_engine::ability::api_type::ApiType>,
1019        can_pay: bool,
1020        targets: &[manabrew_engine::agent::GameEntity],
1021        effect_text: &str,
1022    ) -> bool {
1023        choices::pay_cost_to_prevent_effect(
1024            self,
1025            player,
1026            cost_kind,
1027            message,
1028            source,
1029            api,
1030            can_pay,
1031            targets,
1032            effect_text,
1033        )
1034    }
1035
1036    fn choose_binary(
1037        &mut self,
1038        player: PlayerId,
1039        question: &str,
1040        kind: BinaryChoiceKind,
1041        default_choice: Option<bool>,
1042        source: Option<CardId>,
1043        api: Option<manabrew_engine::ability::api_type::ApiType>,
1044    ) -> bool {
1045        choices::choose_binary(self, player, question, kind, default_choice, source, api)
1046    }
1047
1048    fn choose_phyrexian_pay_life(
1049        &mut self,
1050        player: PlayerId,
1051        color: &str,
1052        source: Option<CardId>,
1053    ) -> bool {
1054        costs::choose_phyrexian_pay_life(self, player, color, source)
1055    }
1056
1057    fn choose_kicker(
1058        &mut self,
1059        player: PlayerId,
1060        kicker_cost: &str,
1061        source: Option<CardId>,
1062    ) -> bool {
1063        costs::choose_kicker(self, player, kicker_cost, source)
1064    }
1065
1066    fn choose_buyback(
1067        &mut self,
1068        player: PlayerId,
1069        buyback_cost: &str,
1070        source: Option<CardId>,
1071    ) -> bool {
1072        costs::choose_buyback(self, player, buyback_cost, source)
1073    }
1074
1075    fn choose_multikicker(
1076        &mut self,
1077        player: PlayerId,
1078        cost: &str,
1079        max_kicks: u32,
1080        source: Option<CardId>,
1081    ) -> u32 {
1082        costs::choose_multikicker(self, player, cost, max_kicks, source)
1083    }
1084
1085    fn choose_replicate(
1086        &mut self,
1087        player: PlayerId,
1088        cost: &str,
1089        max_replicates: u32,
1090        source: Option<CardId>,
1091    ) -> u32 {
1092        costs::choose_replicate(self, player, cost, max_replicates, source)
1093    }
1094
1095    fn choose_color(&mut self, player: PlayerId, valid_colors: &[String]) -> Option<String> {
1096        choices::choose_color(self, player, valid_colors)
1097    }
1098
1099    fn choose_colors(
1100        &mut self,
1101        player: PlayerId,
1102        valid_colors: &[String],
1103        min: usize,
1104        max: usize,
1105    ) -> Vec<String> {
1106        choices::choose_colors(self, player, valid_colors, min, max)
1107    }
1108
1109    fn choose_cards_for_effect(
1110        &mut self,
1111        player: PlayerId,
1112        valid: &[CardId],
1113        min: usize,
1114        max: usize,
1115    ) -> Vec<CardId> {
1116        choices::choose_cards_for_effect(self, player, valid, min, max)
1117    }
1118
1119    fn choose_single_card_for_zone_change(
1120        &mut self,
1121        game: &GameState,
1122        player: PlayerId,
1123        valid: &[CardId],
1124        select_prompt: &str,
1125        is_optional: bool,
1126    ) -> Option<CardId> {
1127        choices::choose_single_card_for_zone_change(
1128            self,
1129            game,
1130            player,
1131            valid,
1132            select_prompt,
1133            is_optional,
1134        )
1135    }
1136
1137    fn choose_cards_for_zone_change(
1138        &mut self,
1139        game: &GameState,
1140        player: PlayerId,
1141        valid: &[CardId],
1142        min: usize,
1143        max: usize,
1144        select_prompt: &str,
1145    ) -> Vec<CardId> {
1146        choices::choose_cards_for_zone_change(self, game, player, valid, min, max, select_prompt)
1147    }
1148
1149    fn choose_type(
1150        &mut self,
1151        player: PlayerId,
1152        type_category: &str,
1153        valid_types: &[String],
1154    ) -> Option<String> {
1155        choices::choose_type(self, player, type_category, valid_types)
1156    }
1157
1158    fn choose_counter_type(
1159        &mut self,
1160        player: PlayerId,
1161        options: &[CounterType],
1162        prompt: &str,
1163    ) -> Option<CounterType> {
1164        choices::choose_counter_type(self, player, options, prompt)
1165    }
1166
1167    fn choose_card_name(&mut self, player: PlayerId, valid_names: &[String]) -> Option<String> {
1168        choices::choose_card_name(self, player, valid_names)
1169    }
1170
1171    fn choose_number(
1172        &mut self,
1173        player: PlayerId,
1174        source: Option<CardId>,
1175        title: &str,
1176        description: Option<&str>,
1177        min: i32,
1178        max: i32,
1179    ) -> Option<i32> {
1180        choices::choose_number(self, player, source, title, description, min, max)
1181    }
1182
1183    fn choose_number_from_list(
1184        &mut self,
1185        player: PlayerId,
1186        choices: &[i32],
1187        message: &str,
1188        source_card_id: Option<CardId>,
1189    ) -> Option<i32> {
1190        choices::choose_number_from_list(self, player, choices, message, source_card_id)
1191    }
1192
1193    fn choose_roll_to_ignore(
1194        &mut self,
1195        player: PlayerId,
1196        rolls: &[i32],
1197        source: Option<CardId>,
1198    ) -> Option<i32> {
1199        choices::choose_roll_to_ignore(self, player, rolls, source)
1200    }
1201
1202    fn choose_roll_to_swap(
1203        &mut self,
1204        player: PlayerId,
1205        rolls: &[i32],
1206        source: Option<CardId>,
1207    ) -> Option<i32> {
1208        choices::choose_roll_to_swap(self, player, rolls, source)
1209    }
1210
1211    fn choose_dice_to_reroll(
1212        &mut self,
1213        player: PlayerId,
1214        rolls: &[i32],
1215        source: Option<CardId>,
1216    ) -> Vec<i32> {
1217        choices::choose_dice_to_reroll(self, player, rolls, source)
1218    }
1219
1220    fn choose_roll_to_modify(
1221        &mut self,
1222        player: PlayerId,
1223        rolls: &[i32],
1224        source: Option<CardId>,
1225    ) -> Option<i32> {
1226        choices::choose_roll_to_modify(self, player, rolls, source)
1227    }
1228
1229    fn choose_roll_swap_value(
1230        &mut self,
1231        player: PlayerId,
1232        current_result: i32,
1233        power: i32,
1234        toughness: i32,
1235        source: Option<CardId>,
1236    ) -> Option<RollSwapChoice> {
1237        choices::choose_roll_swap_value(self, player, current_result, power, toughness, source)
1238    }
1239
1240    fn flip_coin_call(&mut self, player: PlayerId) -> bool {
1241        choices::flip_coin_call(self, player)
1242    }
1243
1244    fn pay_combat_cost(
1245        &mut self,
1246        player: PlayerId,
1247        attacker: CardId,
1248        cost: i32,
1249        description: &str,
1250        mana_ability_options: &[manabrew_engine::agent::ManaAbilityOption],
1251        tappable_lands: &[CardId],
1252        untappable_lands: &[CardId],
1253        mana_pool_total: i32,
1254    ) -> CombatCostAction {
1255        combat::pay_combat_cost(
1256            self,
1257            player,
1258            attacker,
1259            cost,
1260            description,
1261            mana_ability_options,
1262            tappable_lands,
1263            untappable_lands,
1264            mana_pool_total,
1265        )
1266    }
1267
1268    fn choose_improvise(
1269        &mut self,
1270        player: PlayerId,
1271        untapped_artifacts: &[CardId],
1272        remaining_cost: &forge_foundation::ManaCost,
1273        source: Option<CardId>,
1274    ) -> Vec<CardId> {
1275        costs::choose_improvise(self, player, untapped_artifacts, remaining_cost, source)
1276    }
1277
1278    fn choose_convoke(
1279        &mut self,
1280        player: PlayerId,
1281        untapped_creatures: &[CardId],
1282        remaining_cost: &forge_foundation::ManaCost,
1283        source: Option<CardId>,
1284    ) -> Vec<CardId> {
1285        costs::choose_convoke(self, player, untapped_creatures, remaining_cost, source)
1286    }
1287
1288    fn pay_mana_cost(
1289        &mut self,
1290        player: PlayerId,
1291        card_id: CardId,
1292        card_name: &str,
1293        mana_cost: &str,
1294        mana_cost_display: &str,
1295        _mana_cost_checkpoint: &str,
1296        can_confirm_from_pool: bool,
1297        _allow_reserved_source_reuse: bool,
1298        _reserved_sacrifices: &[CardId],
1299        mana_ability_options: &[manabrew_engine::agent::ManaAbilityOption],
1300        tappable_lands: &[CardId],
1301        untappable_lands: &[CardId],
1302        mana_pool: &ManaPool,
1303    ) -> ManaCostAction {
1304        costs::pay_mana_cost(
1305            self,
1306            player,
1307            card_id,
1308            card_name,
1309            mana_cost,
1310            mana_cost_display,
1311            can_confirm_from_pool,
1312            mana_ability_options,
1313            tappable_lands,
1314            untappable_lands,
1315            mana_pool,
1316        )
1317    }
1318
1319    fn await_display_ack(&mut self) {
1320        if self.conceded {
1321            return;
1322        }
1323        if let ClientToServerMessage::Directive { directive } = self.responder.await_ack() {
1324            self.handle_directive(directive);
1325        }
1326    }
1327
1328    fn specify_mana_combo(
1329        &mut self,
1330        player: PlayerId,
1331        available_colors: &[String],
1332        amount: usize,
1333        source: Option<CardId>,
1334        express_choice: Option<u16>,
1335    ) -> Vec<String> {
1336        costs::specify_mana_combo(
1337            self,
1338            player,
1339            available_colors,
1340            amount,
1341            source,
1342            express_choice,
1343        )
1344    }
1345
1346    fn exert_attackers(&mut self, player: PlayerId, attackers: &[CardId]) -> Vec<CardId> {
1347        combat::exert_attackers(self, player, attackers)
1348    }
1349
1350    fn enlist_attackers(&mut self, player: PlayerId, attackers: &[CardId]) -> Vec<CardId> {
1351        combat::enlist_attackers(self, player, attackers)
1352    }
1353
1354    fn choose_reorder_library(
1355        &mut self,
1356        game: &GameState,
1357        player: PlayerId,
1358        cards: &[CardId],
1359    ) -> Vec<CardId> {
1360        library::choose_reorder_library(self, game, player, cards)
1361    }
1362
1363    fn help_pay_assist(&mut self, player: PlayerId, card_name: &str, max_generic: u32) -> u32 {
1364        choices::help_pay_assist(self, player, card_name, max_generic)
1365    }
1366
1367    fn choose_random_discard(
1368        &mut self,
1369        player: PlayerId,
1370        hand: &[CardId],
1371        num: usize,
1372    ) -> Vec<CardId> {
1373        choices::choose_random_discard(self, player, hand, num)
1374    }
1375
1376    fn choose_land_or_spell(&mut self, player: PlayerId) -> Option<bool> {
1377        choices::choose_land_or_spell(self, player)
1378    }
1379
1380    fn notify(&mut self, event: GameNotification) {
1381        match event {
1382            GameNotification::Event(log_event) => {
1383                self.responder
1384                    .send_log(GameLogEntryDto::from_event(log_event));
1385            }
1386            GameNotification::CardPlayed {
1387                player,
1388                card_id,
1389                card_name,
1390                set_code,
1391            } => {
1392                self.emit_display(DisplayEvent::CardPlayed {
1393                    card_id: card_id_str(card_id),
1394                    card_name,
1395                    set_code,
1396                    player_id: player_id_str(player),
1397                });
1398                self.emit_state();
1399            }
1400            GameNotification::TurnChanged {
1401                active_player,
1402                turn_number,
1403            } => {
1404                let player_id = player_id_str(active_player);
1405                let active_player_name = self
1406                    .latest_view
1407                    .as_ref()
1408                    .and_then(|v| v.players.iter().find(|p| p.id == player_id))
1409                    .map(|p| p.name.clone())
1410                    .unwrap_or_else(|| format!("Player {}", active_player.0));
1411                self.responder.send_log(GameLogEntryDto::from_event(
1412                    manabrew_engine::agent::GameLogEvent::rule(format!(
1413                        "TURN {turn_number} — {active_player_name}"
1414                    ))
1415                    .with_player(active_player),
1416                ));
1417                self.emit_display(DisplayEvent::TurnChanged {
1418                    active_player_id: player_id,
1419                    active_player_name,
1420                    turn_number,
1421                });
1422                self.emit_state();
1423            }
1424            GameNotification::PhaseChanged { .. } | GameNotification::StateChanged => {
1425                self.emit_state();
1426            }
1427            GameNotification::PriorityChanged { .. } => {
1428                self.emit_state();
1429            }
1430            GameNotification::FirstPlayerRoll {
1431                sides,
1432                rounds,
1433                winner,
1434            } => {
1435                let view = self.view();
1436                let winner_id = player_id_str(winner);
1437                let mut entries = Vec::new();
1438                let last_round = rounds.len().saturating_sub(1);
1439                for (round_index, round) in rounds.into_iter().enumerate() {
1440                    for (pid, value) in round {
1441                        let id = player_id_str(pid);
1442                        let name = view
1443                            .players
1444                            .iter()
1445                            .find(|p| p.id == id)
1446                            .map(|p| p.name.clone())
1447                            .unwrap_or_else(|| id.clone());
1448                        entries.push(manabrew_protocol::prompts::dice_rolled::DiceRollEntry {
1449                            label: Some(name),
1450                            highlighted: round_index == last_round && id == winner_id,
1451                            player_id: Some(id),
1452                            round: round_index as u32,
1453                            natural_results: vec![value],
1454                            final_results: vec![value],
1455                            ignored_rolls: vec![],
1456                        });
1457                    }
1458                }
1459                self.present_prompt(
1460                    PromptInput::DiceRolled(
1461                        manabrew_protocol::prompts::dice_rolled::DiceRolledInput {
1462                            presentation: PromptPresentation {
1463                                title: "Roll for first player".to_string(),
1464                                description: None,
1465                                text: None,
1466                                targets: Vec::new(),
1467                            },
1468                            sides,
1469                            rolls: entries,
1470                        },
1471                    ),
1472                    None,
1473                );
1474            }
1475            GameNotification::DiceRolled {
1476                player,
1477                sides,
1478                natural_results,
1479                final_results,
1480                ignored_rolls,
1481                source_card_id,
1482            } => {
1483                self.present_prompt(
1484                    PromptInput::DiceRolled(
1485                        manabrew_protocol::prompts::dice_rolled::DiceRolledInput {
1486                            presentation: PromptPresentation {
1487                                title: "Dice roll".to_string(),
1488                                description: None,
1489                                text: None,
1490                                targets: Vec::new(),
1491                            },
1492                            sides,
1493                            rolls: vec![manabrew_protocol::prompts::dice_rolled::DiceRollEntry {
1494                                label: None,
1495                                player_id: Some(player_id_str(player)),
1496                                round: 0,
1497                                natural_results,
1498                                final_results,
1499                                ignored_rolls,
1500                                highlighted: false,
1501                            }],
1502                        },
1503                    ),
1504                    source_card_id,
1505                );
1506            }
1507            GameNotification::SnapshotCreated {
1508                checkpoint_id,
1509                label,
1510            } => {
1511                if let Some(view) = self.latest_view.clone() {
1512                    self.responder.send_snapshot(GameSnapshotEventDto::new(
1513                        checkpoint_id,
1514                        label,
1515                        view,
1516                    ));
1517                }
1518            }
1519            GameNotification::GameOver => {
1520                self.emit_state();
1521                self.present_prompt(
1522                    PromptInput::GameOver(manabrew_protocol::prompts::game_over::GameOverInput {}),
1523                    None,
1524                );
1525            }
1526            GameNotification::ManaPaymentResolved { .. } => {}
1527            GameNotification::ActivatedAbilityPaymentFailed { .. } => {
1528                self.emit_state();
1529            }
1530        }
1531    }
1532
1533    fn take_restore_request(&mut self) -> Option<u64> {
1534        self.pending_restore_checkpoint.take()
1535    }
1536}