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