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