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 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                    | DirectiveInput::StartRecording
707                    | DirectiveInput::StopRecording
708                    | DirectiveInput::RequestRepeat { .. }
709                    | DirectiveInput::RepeatVote { .. },
710            } => Self::default_pass(),
711        };
712        match action {
713            PromptOutput::ChooseAction(ChooseActionOutput::Act { action_id }) => {
714                if let Some(rest) = action_id.strip_prefix("cast:") {
715                    let (id_part, mode) = rest.split_once(':').unwrap_or((rest, "normal"));
716                    let resolved = parse_card_id(id_part).and_then(|cid| {
717                        Self::parse_play_mode(mode)
718                            .and_then(|m| {
719                                playable
720                                    .iter()
721                                    .copied()
722                                    .find(|play| play.card_id == cid && play.mode == m)
723                            })
724                            .or_else(|| playable.iter().copied().find(|play| play.card_id == cid))
725                    });
726                    resolved
727                        .map(EnginePlayerAction::CastSpell)
728                        .unwrap_or(EnginePlayerAction::PassPriority)
729                } else if let Some(rest) = action_id.strip_prefix("tap:") {
730                    let tap = parse_tap_action_id(rest);
731                    match parse_card_id(tap.card_id) {
732                        Some(cid) => EnginePlayerAction::ActivateMana(
733                            cid,
734                            tap.ability_index,
735                            parse_express_mana_choice(tap.color),
736                        ),
737                        None => EnginePlayerAction::PassPriority,
738                    }
739                } else if let Some(rest) = action_id.strip_prefix("ability:") {
740                    let (id_part, idx) = rest.split_once(':').unwrap_or((rest, ""));
741                    match (parse_card_id(id_part), idx.parse::<usize>()) {
742                        (Some(cid), Ok(ability_index)) => {
743                            EnginePlayerAction::ActivateAbility(AbilityRef {
744                                card_id: cid,
745                                ability_index,
746                            })
747                        }
748                        _ => EnginePlayerAction::PassPriority,
749                    }
750                } else if let Some(id_part) = action_id.strip_prefix("untap:") {
751                    parse_card_id(id_part)
752                        .map(EnginePlayerAction::UndoMana)
753                        .unwrap_or(EnginePlayerAction::PassPriority)
754                } else {
755                    EnginePlayerAction::PassPriority
756                }
757            }
758            PromptOutput::ChooseAction(ChooseActionOutput::Pass { until, .. }) => {
759                self.pass_until = until.and_then(|u| {
760                    Some(manabrew_engine::agent::PassUntilTarget {
761                        player: crate::ids_codec::parse_player_id(&u.player_id)?,
762                        phase: crate::game_view_dto::step_to_phase(u.phase),
763                        through_combat: u.through_combat,
764                    })
765                });
766                EnginePlayerAction::PassPriority
767            }
768            _ => EnginePlayerAction::PassPriority,
769        }
770    }
771
772    fn choose_attackers(
773        &mut self,
774        player: PlayerId,
775        available: &[CardId],
776        possible_defenders: &[DefenderId],
777    ) -> Vec<(CardId, DefenderId)> {
778        combat::choose_attackers(self, player, available, possible_defenders)
779    }
780
781    fn choose_blockers(
782        &mut self,
783        player: PlayerId,
784        attackers: &[CardId],
785        available_blockers: &[CardId],
786        max_blockers: Option<usize>,
787    ) -> Vec<(CardId, CardId)> {
788        combat::choose_blockers(self, player, attackers, available_blockers, max_blockers)
789    }
790
791    fn choose_damage_assignment_order(
792        &mut self,
793        player: PlayerId,
794        attacker: CardId,
795        blockers: &[CardId],
796    ) -> Vec<CardId> {
797        combat::choose_damage_assignment_order(self, player, attacker, blockers)
798    }
799
800    fn assign_combat_damage(
801        &mut self,
802        game: &GameState,
803        player: PlayerId,
804        attacker: CardId,
805        blockers_in_order: &[CardId],
806        defender_id: Option<DefenderId>,
807        damage_to_assign: i32,
808    ) -> Vec<(Option<CardId>, i32)> {
809        let attacker_has_deathtouch = game.card(attacker).has_deathtouch();
810        combat::choose_combat_damage_assignment(
811            self,
812            player,
813            attacker,
814            blockers_in_order,
815            defender_id,
816            damage_to_assign,
817            attacker_has_deathtouch,
818        )
819    }
820
821    fn choose_target_player(
822        &mut self,
823        player: PlayerId,
824        valid: &[PlayerId],
825        sa: Option<&manabrew_engine::spellability::SpellAbility>,
826    ) -> Option<PlayerId> {
827        let source = sa.and_then(|s| s.source);
828        let intent = sa
829            .map(crate::game_view_dto::targeting_intent_of)
830            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
831        let hostile = crate::game_view_dto::intent_is_hostile(intent);
832        targeting::choose_target_player(self, player, valid, source, hostile, intent)
833    }
834
835    fn choose_target_card(
836        &mut self,
837        player: PlayerId,
838        valid: &[CardId],
839        sa: Option<&manabrew_engine::spellability::SpellAbility>,
840    ) -> Option<CardId> {
841        let source = sa.and_then(|s| s.source);
842        let intent = sa
843            .map(crate::game_view_dto::targeting_intent_of)
844            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
845        let hostile = crate::game_view_dto::intent_is_hostile(intent);
846        targeting::choose_target_card(self, player, valid, source, hostile, intent)
847    }
848
849    fn choose_target_card_from_zone(
850        &mut self,
851        player: PlayerId,
852        zone: ZoneType,
853        valid: &[CardId],
854        sa: Option<&manabrew_engine::spellability::SpellAbility>,
855    ) -> Option<CardId> {
856        let source = sa.and_then(|s| s.source);
857        let intent = sa
858            .map(crate::game_view_dto::targeting_intent_of)
859            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
860        let hostile = crate::game_view_dto::intent_is_hostile(intent);
861        targeting::choose_target_card_from_zone(self, player, zone, valid, source, hostile, intent)
862    }
863
864    fn choose_target_any(
865        &mut self,
866        player: PlayerId,
867        valid_players: &[PlayerId],
868        valid_cards: &[CardId],
869        sa: Option<&manabrew_engine::spellability::SpellAbility>,
870    ) -> TargetChoice {
871        let source = sa.and_then(|s| s.source);
872        let intent = sa
873            .map(crate::game_view_dto::targeting_intent_of)
874            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
875        let hostile = crate::game_view_dto::intent_is_hostile(intent);
876        targeting::choose_target_any(
877            self,
878            player,
879            valid_players,
880            valid_cards,
881            source,
882            hostile,
883            intent,
884        )
885    }
886
887    fn choose_sacrifice(
888        &mut self,
889        player: PlayerId,
890        valid: &[CardId],
891        source: Option<CardId>,
892    ) -> Option<CardId> {
893        targeting::choose_sacrifice(self, player, valid, source)
894    }
895
896    fn reveal_cards(
897        &mut self,
898        game: &GameState,
899        _player: PlayerId,
900        cards: &[CardId],
901        zone: ZoneType,
902        owner: PlayerId,
903        message_prefix: Option<&str>,
904    ) {
905        choices::reveal_cards(self, game, cards, zone, owner, message_prefix)
906    }
907
908    fn choose_scry(
909        &mut self,
910        game: &GameState,
911        player: PlayerId,
912        source: Option<CardId>,
913        cards: &[CardId],
914    ) -> Vec<Vec<CardId>> {
915        library::choose_scry(self, game, player, source, cards)
916    }
917
918    fn choose_surveil(
919        &mut self,
920        game: &GameState,
921        player: PlayerId,
922        source: Option<CardId>,
923        cards: &[CardId],
924    ) -> Vec<Vec<CardId>> {
925        library::choose_surveil(self, game, player, source, cards)
926    }
927
928    fn choose_dig(
929        &mut self,
930        game: &GameState,
931        player: PlayerId,
932        valid: &[CardId],
933        max: usize,
934        optional: bool,
935    ) -> Vec<CardId> {
936        library::choose_dig(self, game, player, valid, max, optional)
937    }
938
939    fn choose_discard(&mut self, player: PlayerId, hand: &[CardId], num: usize) -> Vec<CardId> {
940        choices::choose_discard(self, player, hand, num)
941    }
942
943    fn choose_discard_any_number(
944        &mut self,
945        player: PlayerId,
946        hand: &[CardId],
947        min: usize,
948        max: usize,
949    ) -> Vec<CardId> {
950        choices::choose_discard_any_number(self, player, hand, min, max)
951    }
952
953    fn choose_legend_keep(&mut self, player: PlayerId, duplicates: &[CardId]) -> CardId {
954        choices::choose_legend_keep(self, player, duplicates)
955    }
956
957    fn choose_target_spell(
958        &mut self,
959        player: PlayerId,
960        valid: &[u32],
961        source: Option<CardId>,
962    ) -> Option<u32> {
963        targeting::choose_target_spell(self, player, valid, source)
964    }
965
966    fn choose_mode(
967        &mut self,
968        player: PlayerId,
969        descriptions: &[String],
970        min: usize,
971        max: usize,
972        source_card_id: Option<CardId>,
973    ) -> Vec<usize> {
974        choices::choose_mode(self, player, descriptions, min, max, source_card_id)
975    }
976
977    fn choose_spell_abilities_for_effect(
978        &mut self,
979        player: PlayerId,
980        abilities: &[manabrew_engine::spellability::SpellAbility],
981        num: usize,
982    ) -> Vec<usize> {
983        choices::choose_spell_abilities_for_effect(self, player, abilities, num)
984    }
985
986    fn get_ability_to_play(
987        &mut self,
988        player: PlayerId,
989        abilities: &[manabrew_engine::spellability::SpellAbility],
990    ) -> Option<usize> {
991        choices::get_ability_to_play(self, player, abilities)
992    }
993
994    fn choose_single_entity_for_effect(
995        &mut self,
996        player: PlayerId,
997        valid: &[GameEntity],
998        is_optional: bool,
999    ) -> Option<GameEntity> {
1000        choices::choose_single_entity_for_effect(self, player, valid, is_optional)
1001    }
1002
1003    fn choose_entities_for_effect(
1004        &mut self,
1005        player: PlayerId,
1006        candidates: &[GameEntity],
1007        min: usize,
1008        max: usize,
1009    ) -> Vec<GameEntity> {
1010        choices::choose_entities_for_effect(self, player, candidates, min, max)
1011    }
1012
1013    fn choose_single_replacement_effect(
1014        &mut self,
1015        player: PlayerId,
1016        descriptions: &[String],
1017    ) -> usize {
1018        choices::choose_single_replacement_effect(self, player, descriptions)
1019    }
1020
1021    fn confirm_replacement_effect(
1022        &mut self,
1023        player: PlayerId,
1024        question: &str,
1025        effect_description: &str,
1026        source: Option<CardId>,
1027    ) -> bool {
1028        choices::confirm_replacement_effect(self, player, question, effect_description, source)
1029    }
1030
1031    fn choose_optional_trigger(
1032        &mut self,
1033        player: PlayerId,
1034        description: &str,
1035        source: Option<CardId>,
1036        api: Option<manabrew_engine::ability::api_type::ApiType>,
1037    ) -> bool {
1038        choices::choose_optional_trigger(self, player, description, source, api)
1039    }
1040
1041    fn confirm_action(
1042        &mut self,
1043        player: PlayerId,
1044        mode: Option<&str>,
1045        message: &str,
1046        options: &[String],
1047        source: Option<CardId>,
1048        api: Option<manabrew_engine::ability::api_type::ApiType>,
1049    ) -> bool {
1050        choices::confirm_action(self, player, mode, message, options, source, api)
1051    }
1052
1053    fn confirm_payment(
1054        &mut self,
1055        player: PlayerId,
1056        cost_kind: &str,
1057        message: &str,
1058        source: Option<CardId>,
1059        api: Option<manabrew_engine::ability::api_type::ApiType>,
1060    ) -> bool {
1061        choices::confirm_payment(self, player, cost_kind, message, source, api)
1062    }
1063
1064    fn pay_cost_to_prevent_effect(
1065        &mut self,
1066        player: PlayerId,
1067        cost_kind: &str,
1068        message: &str,
1069        source: Option<CardId>,
1070        api: Option<manabrew_engine::ability::api_type::ApiType>,
1071        can_pay: bool,
1072        targets: &[manabrew_engine::agent::GameEntity],
1073        effect_text: &str,
1074    ) -> bool {
1075        choices::pay_cost_to_prevent_effect(
1076            self,
1077            player,
1078            cost_kind,
1079            message,
1080            source,
1081            api,
1082            can_pay,
1083            targets,
1084            effect_text,
1085        )
1086    }
1087
1088    fn choose_binary(
1089        &mut self,
1090        player: PlayerId,
1091        question: &str,
1092        kind: BinaryChoiceKind,
1093        default_choice: Option<bool>,
1094        source: Option<CardId>,
1095        api: Option<manabrew_engine::ability::api_type::ApiType>,
1096    ) -> bool {
1097        choices::choose_binary(self, player, question, kind, default_choice, source, api)
1098    }
1099
1100    fn choose_phyrexian_pay_life(
1101        &mut self,
1102        player: PlayerId,
1103        color: &str,
1104        source: Option<CardId>,
1105    ) -> bool {
1106        costs::choose_phyrexian_pay_life(self, player, color, source)
1107    }
1108
1109    fn choose_kicker(
1110        &mut self,
1111        player: PlayerId,
1112        kicker_cost: &str,
1113        source: Option<CardId>,
1114    ) -> bool {
1115        costs::choose_kicker(self, player, kicker_cost, source)
1116    }
1117
1118    fn choose_buyback(
1119        &mut self,
1120        player: PlayerId,
1121        buyback_cost: &str,
1122        source: Option<CardId>,
1123    ) -> bool {
1124        costs::choose_buyback(self, player, buyback_cost, source)
1125    }
1126
1127    fn choose_multikicker(
1128        &mut self,
1129        player: PlayerId,
1130        cost: &str,
1131        max_kicks: u32,
1132        source: Option<CardId>,
1133    ) -> u32 {
1134        costs::choose_multikicker(self, player, cost, max_kicks, source)
1135    }
1136
1137    fn choose_replicate(
1138        &mut self,
1139        player: PlayerId,
1140        cost: &str,
1141        max_replicates: u32,
1142        source: Option<CardId>,
1143    ) -> u32 {
1144        costs::choose_replicate(self, player, cost, max_replicates, source)
1145    }
1146
1147    fn choose_color(&mut self, player: PlayerId, valid_colors: &[String]) -> Option<String> {
1148        choices::choose_color(self, player, valid_colors)
1149    }
1150
1151    fn choose_colors(
1152        &mut self,
1153        player: PlayerId,
1154        valid_colors: &[String],
1155        min: usize,
1156        max: usize,
1157    ) -> Vec<String> {
1158        choices::choose_colors(self, player, valid_colors, min, max)
1159    }
1160
1161    fn choose_cards_for_effect(
1162        &mut self,
1163        player: PlayerId,
1164        valid: &[CardId],
1165        min: usize,
1166        max: usize,
1167    ) -> Vec<CardId> {
1168        choices::choose_cards_for_effect(self, player, valid, min, max)
1169    }
1170
1171    fn choose_single_card_for_zone_change(
1172        &mut self,
1173        game: &GameState,
1174        player: PlayerId,
1175        valid: &[CardId],
1176        select_prompt: &str,
1177        is_optional: bool,
1178    ) -> Option<CardId> {
1179        choices::choose_single_card_for_zone_change(
1180            self,
1181            game,
1182            player,
1183            valid,
1184            select_prompt,
1185            is_optional,
1186        )
1187    }
1188
1189    fn choose_cards_for_zone_change(
1190        &mut self,
1191        game: &GameState,
1192        player: PlayerId,
1193        valid: &[CardId],
1194        min: usize,
1195        max: usize,
1196        select_prompt: &str,
1197    ) -> Vec<CardId> {
1198        choices::choose_cards_for_zone_change(self, game, player, valid, min, max, select_prompt)
1199    }
1200
1201    fn choose_type(
1202        &mut self,
1203        player: PlayerId,
1204        type_category: &str,
1205        valid_types: &[String],
1206    ) -> Option<String> {
1207        choices::choose_type(self, player, type_category, valid_types)
1208    }
1209
1210    fn choose_counter_type(
1211        &mut self,
1212        player: PlayerId,
1213        options: &[CounterType],
1214        prompt: &str,
1215    ) -> Option<CounterType> {
1216        choices::choose_counter_type(self, player, options, prompt)
1217    }
1218
1219    fn choose_card_name(&mut self, player: PlayerId, valid_names: &[String]) -> Option<String> {
1220        choices::choose_card_name(self, player, valid_names)
1221    }
1222
1223    fn choose_number(
1224        &mut self,
1225        player: PlayerId,
1226        source: Option<CardId>,
1227        title: &str,
1228        description: Option<&str>,
1229        min: i32,
1230        max: i32,
1231    ) -> Option<i32> {
1232        choices::choose_number(self, player, source, title, description, min, max)
1233    }
1234
1235    fn choose_number_from_list(
1236        &mut self,
1237        player: PlayerId,
1238        choices: &[i32],
1239        message: &str,
1240        source_card_id: Option<CardId>,
1241    ) -> Option<i32> {
1242        choices::choose_number_from_list(self, player, choices, message, source_card_id)
1243    }
1244
1245    fn choose_roll_to_ignore(
1246        &mut self,
1247        player: PlayerId,
1248        rolls: &[i32],
1249        source: Option<CardId>,
1250    ) -> Option<i32> {
1251        choices::choose_roll_to_ignore(self, player, rolls, source)
1252    }
1253
1254    fn choose_roll_to_swap(
1255        &mut self,
1256        player: PlayerId,
1257        rolls: &[i32],
1258        source: Option<CardId>,
1259    ) -> Option<i32> {
1260        choices::choose_roll_to_swap(self, player, rolls, source)
1261    }
1262
1263    fn choose_dice_to_reroll(
1264        &mut self,
1265        player: PlayerId,
1266        rolls: &[i32],
1267        source: Option<CardId>,
1268    ) -> Vec<i32> {
1269        choices::choose_dice_to_reroll(self, player, rolls, source)
1270    }
1271
1272    fn choose_roll_to_modify(
1273        &mut self,
1274        player: PlayerId,
1275        rolls: &[i32],
1276        source: Option<CardId>,
1277    ) -> Option<i32> {
1278        choices::choose_roll_to_modify(self, player, rolls, source)
1279    }
1280
1281    fn choose_roll_swap_value(
1282        &mut self,
1283        player: PlayerId,
1284        current_result: i32,
1285        power: i32,
1286        toughness: i32,
1287        source: Option<CardId>,
1288    ) -> Option<RollSwapChoice> {
1289        choices::choose_roll_swap_value(self, player, current_result, power, toughness, source)
1290    }
1291
1292    fn flip_coin_call(&mut self, player: PlayerId) -> bool {
1293        choices::flip_coin_call(self, player)
1294    }
1295
1296    fn pay_combat_cost(
1297        &mut self,
1298        player: PlayerId,
1299        attacker: CardId,
1300        cost: i32,
1301        description: &str,
1302        mana_ability_options: &[manabrew_engine::agent::ManaAbilityOption],
1303        tappable_lands: &[CardId],
1304        untappable_lands: &[CardId],
1305        mana_pool_total: i32,
1306    ) -> CombatCostAction {
1307        combat::pay_combat_cost(
1308            self,
1309            player,
1310            attacker,
1311            cost,
1312            description,
1313            mana_ability_options,
1314            tappable_lands,
1315            untappable_lands,
1316            mana_pool_total,
1317        )
1318    }
1319
1320    fn choose_improvise(
1321        &mut self,
1322        player: PlayerId,
1323        untapped_artifacts: &[CardId],
1324        remaining_cost: &forge_foundation::ManaCost,
1325        source: Option<CardId>,
1326    ) -> Vec<CardId> {
1327        costs::choose_improvise(self, player, untapped_artifacts, remaining_cost, source)
1328    }
1329
1330    fn choose_convoke(
1331        &mut self,
1332        player: PlayerId,
1333        untapped_creatures: &[CardId],
1334        remaining_cost: &forge_foundation::ManaCost,
1335        source: Option<CardId>,
1336    ) -> Vec<CardId> {
1337        costs::choose_convoke(self, player, untapped_creatures, remaining_cost, source)
1338    }
1339
1340    fn pay_mana_cost(
1341        &mut self,
1342        player: PlayerId,
1343        card_id: CardId,
1344        card_name: &str,
1345        mana_cost: &str,
1346        mana_cost_display: &str,
1347        _mana_cost_checkpoint: &str,
1348        can_confirm_from_pool: bool,
1349        _allow_reserved_source_reuse: bool,
1350        _reserved_sacrifices: &[CardId],
1351        mana_ability_options: &[manabrew_engine::agent::ManaAbilityOption],
1352        tappable_lands: &[CardId],
1353        untappable_lands: &[CardId],
1354        mana_pool: &ManaPool,
1355    ) -> ManaCostAction {
1356        costs::pay_mana_cost(
1357            self,
1358            player,
1359            card_id,
1360            card_name,
1361            mana_cost,
1362            mana_cost_display,
1363            can_confirm_from_pool,
1364            mana_ability_options,
1365            tappable_lands,
1366            untappable_lands,
1367            mana_pool,
1368        )
1369    }
1370
1371    fn await_display_ack(&mut self) {
1372        if self.conceded {
1373            return;
1374        }
1375        if let ClientToServerMessage::Directive { directive } = self.responder.await_ack() {
1376            self.handle_directive(directive);
1377        }
1378    }
1379
1380    fn specify_mana_combo(
1381        &mut self,
1382        player: PlayerId,
1383        available_colors: &[String],
1384        amount: usize,
1385        source: Option<CardId>,
1386        express_choice: Option<u16>,
1387    ) -> Vec<String> {
1388        costs::specify_mana_combo(
1389            self,
1390            player,
1391            available_colors,
1392            amount,
1393            source,
1394            express_choice,
1395        )
1396    }
1397
1398    fn exert_attackers(&mut self, player: PlayerId, attackers: &[CardId]) -> Vec<CardId> {
1399        combat::exert_attackers(self, player, attackers)
1400    }
1401
1402    fn enlist_attackers(&mut self, player: PlayerId, attackers: &[CardId]) -> Vec<CardId> {
1403        combat::enlist_attackers(self, player, attackers)
1404    }
1405
1406    fn choose_reorder_library(
1407        &mut self,
1408        game: &GameState,
1409        player: PlayerId,
1410        cards: &[CardId],
1411    ) -> Vec<CardId> {
1412        library::choose_reorder_library(self, game, player, cards)
1413    }
1414
1415    fn help_pay_assist(&mut self, player: PlayerId, card_name: &str, max_generic: u32) -> u32 {
1416        choices::help_pay_assist(self, player, card_name, max_generic)
1417    }
1418
1419    fn choose_random_discard(
1420        &mut self,
1421        player: PlayerId,
1422        hand: &[CardId],
1423        num: usize,
1424    ) -> Vec<CardId> {
1425        choices::choose_random_discard(self, player, hand, num)
1426    }
1427
1428    fn choose_land_or_spell(&mut self, player: PlayerId) -> Option<bool> {
1429        choices::choose_land_or_spell(self, player)
1430    }
1431
1432    fn notify(&mut self, event: GameNotification) {
1433        match event {
1434            GameNotification::Event(log_event) => {
1435                self.responder
1436                    .send_log(GameLogEntryDto::from_event(log_event));
1437            }
1438            GameNotification::CardPlayed => {
1439                self.emit_state();
1440            }
1441            GameNotification::TurnChanged {
1442                active_player,
1443                turn_number,
1444            } => {
1445                let player_id = player_id_str(active_player);
1446                let active_player_name = self
1447                    .latest_view
1448                    .as_ref()
1449                    .and_then(|view| view.players.iter().find(|player| player.id == player_id))
1450                    .map(|player| player.name.clone())
1451                    .unwrap_or_else(|| format!("Player {}", active_player.0));
1452                self.responder.send_log(GameLogEntryDto::from_event(
1453                    manabrew_engine::agent::GameLogEvent::rule(format!(
1454                        "TURN {turn_number} — {active_player_name}"
1455                    ))
1456                    .with_player(active_player),
1457                ));
1458                self.emit_state();
1459            }
1460            GameNotification::PhaseChanged { .. } | GameNotification::StateChanged => {
1461                self.emit_state();
1462            }
1463            GameNotification::PriorityChanged { .. } => {
1464                self.emit_state();
1465            }
1466            GameNotification::FirstPlayerRoll {
1467                sides,
1468                rounds,
1469                winner,
1470            } => {
1471                let view = self.view();
1472                let winner_id = player_id_str(winner);
1473                let mut entries = Vec::new();
1474                let last_round = rounds.len().saturating_sub(1);
1475                for (round_index, round) in rounds.into_iter().enumerate() {
1476                    for (pid, value) in round {
1477                        let id = player_id_str(pid);
1478                        let name = view
1479                            .players
1480                            .iter()
1481                            .find(|p| p.id == id)
1482                            .map(|p| p.name.clone())
1483                            .unwrap_or_else(|| id.clone());
1484                        entries.push(manabrew_protocol::prompts::dice_rolled::DiceRollEntry {
1485                            label: Some(name),
1486                            highlighted: round_index == last_round && id == winner_id,
1487                            player_id: Some(id),
1488                            round: round_index as u32,
1489                            natural_results: vec![value],
1490                            final_results: vec![value],
1491                            ignored_rolls: vec![],
1492                        });
1493                    }
1494                }
1495                self.present_prompt(
1496                    PromptInput::DiceRolled(
1497                        manabrew_protocol::prompts::dice_rolled::DiceRolledInput {
1498                            presentation: PromptPresentation {
1499                                title: "Roll for first player".to_string(),
1500                                description: None,
1501                                text: None,
1502                                targets: Vec::new(),
1503                            },
1504                            sides,
1505                            rolls: entries,
1506                        },
1507                    ),
1508                    None,
1509                );
1510            }
1511            GameNotification::DiceRolled {
1512                player,
1513                sides,
1514                natural_results,
1515                final_results,
1516                ignored_rolls,
1517                source_card_id,
1518            } => {
1519                self.present_prompt(
1520                    PromptInput::DiceRolled(
1521                        manabrew_protocol::prompts::dice_rolled::DiceRolledInput {
1522                            presentation: PromptPresentation {
1523                                title: "Dice roll".to_string(),
1524                                description: None,
1525                                text: None,
1526                                targets: Vec::new(),
1527                            },
1528                            sides,
1529                            rolls: vec![manabrew_protocol::prompts::dice_rolled::DiceRollEntry {
1530                                label: None,
1531                                player_id: Some(player_id_str(player)),
1532                                round: 0,
1533                                natural_results,
1534                                final_results,
1535                                ignored_rolls,
1536                                highlighted: false,
1537                            }],
1538                        },
1539                    ),
1540                    source_card_id,
1541                );
1542            }
1543            GameNotification::SnapshotCreated {
1544                checkpoint_id,
1545                label,
1546            } => {
1547                if let Some(view) = self.latest_view.clone() {
1548                    self.responder.send_snapshot(GameSnapshotEventDto::new(
1549                        checkpoint_id,
1550                        label,
1551                        view,
1552                    ));
1553                }
1554            }
1555            GameNotification::GameOver => {
1556                self.emit_state();
1557                self.present_prompt(
1558                    PromptInput::GameOver(manabrew_protocol::prompts::game_over::GameOverInput {}),
1559                    None,
1560                );
1561            }
1562            GameNotification::ManaPaymentResolved { .. } => {}
1563            GameNotification::ActivatedAbilityPaymentFailed { .. } => {
1564                self.emit_state();
1565            }
1566        }
1567    }
1568}