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