Skip to main content

manabrew_agent_interface/
protocol.rs

1use crate::game_log_event::GameLogEntryDto;
2use crate::game_snapshot_event::GameSnapshotEventDto;
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6// Wire types (ClientMessage, ServerMessage, RoomInfo, …) live in
7// manabrew-relay-protocol; StateEnvelope stays here because it carries engine DTOs.
8pub use manabrew_relay_protocol::*;
9
10/// Typed envelope carried inside `ClientMessage::BroadcastState.state` /
11/// `ServerMessage::StateUpdate.state`. One discriminator (`kind`) plus the
12/// payload for that variant. Constructed and parsed in every layer that
13/// touches the relay (engine, bot, host, web/Tauri UI) — anything that needs
14/// to handcraft `json!({"kind": "..."})` belongs here instead.
15#[derive(Debug, Clone, Serialize, Deserialize)]
16#[serde(tag = "kind", rename_all = "camelCase")]
17pub enum StateEnvelope {
18    State {
19        #[serde(rename = "forPlayer", default, skip_serializing_if = "Option::is_none")]
20        for_player: Option<String>,
21        state: Value,
22        /// Milliseconds the engine host spent between receiving the response
23        /// that caused this state and sending it. Lets a receiver separate
24        /// engine work from the hop to the engine host, which is otherwise
25        /// impossible: only the relay stamps these envelopes, and comparing
26        /// clocks across hosts is not something we want to rely on.
27        #[serde(rename = "engineMs", default, skip_serializing_if = "Option::is_none")]
28        engine_ms: Option<u32>,
29        /// Milliseconds the engine host then spent building this envelope:
30        /// serialising the state, fingerprinting it, diffing it. Sampled after
31        /// `engine_ms`, so subtracting both from a relay-stamped round trip
32        /// leaves the hop alone. Otherwise that work reads as network, and
33        /// unlike the network it grows with the board. Always `None` here: the
34        /// value is stamped onto the serialised envelope by the sender, which
35        /// cannot know it until the serialising is done.
36        #[serde(rename = "emitMs", default, skip_serializing_if = "Option::is_none")]
37        emit_ms: Option<u32>,
38        /// Set only when the sender also emits [`StateEnvelope::StateDelta`],
39        /// so a receiver can tell whether a later patch applies to what it
40        /// holds. Receivers never compute it: the sender is the only authority,
41        /// which keeps Rust and TypeScript from having to agree on a hash.
42        #[serde(default, skip_serializing_if = "Option::is_none")]
43        fingerprint: Option<String>,
44    },
45    /// Patch turning the receiver's previous state into the current one, as
46    /// produced by [`crate::state_delta::diff`]. `base` is the fingerprint of
47    /// the state it applies to; a receiver holding a different one must ask for
48    /// a full [`StateEnvelope::State`] rather than apply the patch.
49    StateDelta {
50        #[serde(rename = "forPlayer", default, skip_serializing_if = "Option::is_none")]
51        for_player: Option<String>,
52        base: String,
53        fingerprint: String,
54        patch: Value,
55        #[serde(rename = "engineMs", default, skip_serializing_if = "Option::is_none")]
56        engine_ms: Option<u32>,
57        /// See [`StateEnvelope::State::emit_ms`]. Stamped after the patch is
58        /// built, so it covers the diff that produced this envelope.
59        #[serde(rename = "emitMs", default, skip_serializing_if = "Option::is_none")]
60        emit_ms: Option<u32>,
61    },
62    Display {
63        event: Value,
64    },
65    /// Engine asks a player for a decision. `prompt` is `AgentPrompt` for the
66    /// Rust engine; the Java bridge emits a different shape, so the payload is
67    /// kept as raw `Value` here and parsed by the receiver.
68    Prompt {
69        #[serde(rename = "forPlayer")]
70        for_player: String,
71        prompt: Value,
72        #[serde(rename = "engineMs", default, skip_serializing_if = "Option::is_none")]
73        engine_ms: Option<u32>,
74        /// See [`StateEnvelope::State::emit_ms`].
75        #[serde(rename = "emitMs", default, skip_serializing_if = "Option::is_none")]
76        emit_ms: Option<u32>,
77    },
78    /// Player answers a prompt. `action` is `PlayerAction` for Rust; raw value
79    Response {
80        #[serde(rename = "fromPlayer")]
81        from_player: String,
82        #[serde(rename = "promptId", default)]
83        prompt_id: u32,
84        action: Value,
85    },
86    Directive {
87        #[serde(rename = "fromPlayer")]
88        from_player: String,
89        directive: Value,
90    },
91    EngineDirective {
92        #[serde(rename = "forPlayer")]
93        for_player: String,
94        directive: Value,
95    },
96    /// Engine log entry broadcast to observers.
97    Log {
98        #[serde(rename = "fromPlayer")]
99        from_player: String,
100        entry: GameLogEntryDto,
101    },
102    /// Engine snapshot broadcast to observers.
103    Snapshot {
104        #[serde(rename = "fromPlayer")]
105        from_player: String,
106        entry: Box<GameSnapshotEventDto>,
107    },
108    Fatal {
109        message: String,
110    },
111    /// Engine rejects a response (stale prompt, wrong player, unknown action).
112    /// `error` is `ProtocolError`; recoverable unless the session is terminated.
113    Error {
114        #[serde(rename = "forPlayer")]
115        for_player: String,
116        error: Value,
117    },
118    /// Out-of-band message tunneled through the relay (manual tabletop launch,
119    /// self-hosted-node control plane, heartbeats, …). The relay never
120    /// interprets the `payload`.
121    RoomRelay {
122        protocol: String,
123        version: u32,
124        #[serde(rename = "messageId")]
125        message_id: String,
126        #[serde(
127            rename = "fromPlayer",
128            default,
129            skip_serializing_if = "Option::is_none"
130        )]
131        from_player: Option<String>,
132        #[serde(
133            rename = "targetPlayer",
134            default,
135            skip_serializing_if = "Option::is_none"
136        )]
137        target_player: Option<String>,
138        #[serde(rename = "roomId", default, skip_serializing_if = "Option::is_none")]
139        room_id: Option<String>,
140        payload: Value,
141    },
142}
143
144impl StateEnvelope {
145    pub fn for_agent_message(for_player: String, message: &crate::prompt::AgentMessage) -> Self {
146        Self::for_agent_message_timed(for_player, message, None)
147    }
148
149    /// As [`Self::for_agent_message`], carrying how long the engine host took
150    /// to produce this message.
151    pub fn for_agent_message_timed(
152        for_player: String,
153        message: &crate::prompt::AgentMessage,
154        engine_ms: Option<u32>,
155    ) -> Self {
156        use crate::prompt::AgentMessage;
157        match message {
158            AgentMessage::State(state) => StateEnvelope::State {
159                for_player: Some(for_player),
160                state: serde_json::to_value(state).unwrap_or(Value::Null),
161                fingerprint: None,
162                engine_ms,
163                emit_ms: None,
164            },
165            AgentMessage::Display(event) => StateEnvelope::Display {
166                event: serde_json::to_value(event).unwrap_or(Value::Null),
167            },
168            AgentMessage::Prompt(prompt) => StateEnvelope::Prompt {
169                for_player,
170                prompt: serde_json::to_value(prompt).unwrap_or(Value::Null),
171                engine_ms,
172                emit_ms: None,
173            },
174            AgentMessage::Directive(directive) => StateEnvelope::EngineDirective {
175                for_player,
176                directive: serde_json::to_value(directive).unwrap_or(Value::Null),
177            },
178            AgentMessage::Error(error) => StateEnvelope::Error {
179                for_player,
180                error: serde_json::to_value(error).unwrap_or(Value::Null),
181            },
182        }
183    }
184}