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 /// Engine asks a player for a decision. `prompt` is `AgentPrompt` for the
63 /// Rust engine; the Java bridge emits a different shape, so the payload is
64 /// kept as raw `Value` here and parsed by the receiver.
65 Prompt {
66 #[serde(rename = "forPlayer")]
67 for_player: String,
68 prompt: Value,
69 #[serde(rename = "engineMs", default, skip_serializing_if = "Option::is_none")]
70 engine_ms: Option<u32>,
71 /// See [`StateEnvelope::State::emit_ms`].
72 #[serde(rename = "emitMs", default, skip_serializing_if = "Option::is_none")]
73 emit_ms: Option<u32>,
74 },
75 /// Player answers a prompt. `action` is `PlayerAction` for Rust; raw value
76 Response {
77 #[serde(rename = "fromPlayer")]
78 from_player: String,
79 #[serde(rename = "promptId", default)]
80 prompt_id: u32,
81 action: Value,
82 },
83 Directive {
84 #[serde(rename = "fromPlayer")]
85 from_player: String,
86 directive: Value,
87 },
88 EngineDirective {
89 #[serde(rename = "forPlayer")]
90 for_player: String,
91 directive: Value,
92 },
93 /// Engine log entry broadcast to observers.
94 Log {
95 #[serde(rename = "fromPlayer")]
96 from_player: String,
97 entry: GameLogEntryDto,
98 },
99 /// Engine snapshot broadcast to observers.
100 Snapshot {
101 #[serde(rename = "fromPlayer")]
102 from_player: String,
103 entry: Box<GameSnapshotEventDto>,
104 },
105 Fatal {
106 message: String,
107 },
108 /// Engine rejects a response (stale prompt, wrong player, unknown action).
109 /// `error` is `ProtocolError`; recoverable unless the session is terminated.
110 Error {
111 #[serde(rename = "forPlayer")]
112 for_player: String,
113 error: Value,
114 },
115 /// Out-of-band message tunneled through the relay (manual tabletop launch,
116 /// self-hosted-node control plane, heartbeats, …). The relay never
117 /// interprets the `payload`.
118 RoomRelay {
119 protocol: String,
120 version: u32,
121 #[serde(rename = "messageId")]
122 message_id: String,
123 #[serde(
124 rename = "fromPlayer",
125 default,
126 skip_serializing_if = "Option::is_none"
127 )]
128 from_player: Option<String>,
129 #[serde(
130 rename = "targetPlayer",
131 default,
132 skip_serializing_if = "Option::is_none"
133 )]
134 target_player: Option<String>,
135 #[serde(rename = "roomId", default, skip_serializing_if = "Option::is_none")]
136 room_id: Option<String>,
137 payload: Value,
138 },
139}
140
141impl StateEnvelope {
142 pub fn for_agent_message(for_player: String, message: &crate::prompt::AgentMessage) -> Self {
143 Self::for_agent_message_timed(for_player, message, None)
144 }
145
146 /// As [`Self::for_agent_message`], carrying how long the engine host took
147 /// to produce this message.
148 pub fn for_agent_message_timed(
149 for_player: String,
150 message: &crate::prompt::AgentMessage,
151 engine_ms: Option<u32>,
152 ) -> Self {
153 use crate::prompt::AgentMessage;
154 match message {
155 AgentMessage::State(state) => StateEnvelope::State {
156 for_player: Some(for_player),
157 state: serde_json::to_value(state).unwrap_or(Value::Null),
158 fingerprint: None,
159 engine_ms,
160 emit_ms: None,
161 },
162 AgentMessage::Prompt(prompt) => StateEnvelope::Prompt {
163 for_player,
164 prompt: serde_json::to_value(prompt).unwrap_or(Value::Null),
165 engine_ms,
166 emit_ms: None,
167 },
168 AgentMessage::Directive(directive) => StateEnvelope::EngineDirective {
169 for_player,
170 directive: serde_json::to_value(directive).unwrap_or(Value::Null),
171 },
172 AgentMessage::Error(error) => StateEnvelope::Error {
173 for_player,
174 error: serde_json::to_value(error).unwrap_or(Value::Null),
175 },
176 }
177 }
178}