Skip to main content

infinity_agent_core/
message.rs

1use infinity_provider_protocol::message::{
2    AssistantContent, Message, ToolCall, ToolResult, UserContent,
3};
4use rap_protocol::ThreadId;
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Deserialize, Serialize, Clone)]
8#[serde(untagged)]
9pub enum InputMessageContent {
10    OAuth(OAuthRequired),
11    UserChoice(UserChoiceRequired),
12    User(UserContent),
13}
14
15#[derive(Debug, Deserialize, Serialize, Clone)]
16pub struct OAuthRequired {
17    #[serde(rename = "type")]
18    pub content_type: String,
19    pub id: String,
20    pub call_id: Option<String>,
21    pub auth_url: String,
22}
23
24#[derive(Debug, Deserialize, Serialize, Clone)]
25pub struct UserChoiceRequired {
26    #[serde(rename = "type")]
27    pub content_type: String,
28    pub id: String,
29    pub call_id: Option<String>,
30    pub prompt: String,
31    pub choices: Vec<String>,
32    pub default: usize,
33    pub response_url: String,
34}
35
36/// Distinguishes subscription events (which spawn a subthread) from thread reports
37/// (which inject directly into the target thread).
38/// A plain string deserializes as SubscriptionEvent for backward compatibility.
39#[derive(Debug, Deserialize, Serialize, Clone)]
40#[serde(untagged)]
41pub enum SyntheticKind {
42    Tagged(TaggedSyntheticKind),
43    /// Backward compat: a bare string is treated as a subscription event
44    SubscriptionEvent(String),
45}
46
47#[derive(Debug, Deserialize, Serialize, Clone)]
48#[serde(tag = "type")]
49pub enum TaggedSyntheticKind {
50    #[serde(rename = "subscription_event")]
51    SubscriptionEvent {
52        tool_call_id: String,
53        #[serde(default)]
54        associative: bool,
55        /// When true, this is the final event — the runtime removes the
56        /// subscription from active tracking.
57        #[serde(default)]
58        r#final: bool,
59    },
60    #[serde(rename = "thread_report")]
61    ThreadReport {
62        tool_call_id: String,
63        child_thread_id: ThreadId,
64    },
65    #[serde(rename = "parent_message")]
66    ParentMessage { tool_call_id: String },
67    #[serde(rename = "compaction")]
68    Compaction,
69    #[serde(rename = "compaction_complete")]
70    CompactionComplete,
71}
72
73impl SyntheticKind {
74    pub fn tool_call_id(&self) -> &str {
75        match self {
76            SyntheticKind::Tagged(TaggedSyntheticKind::SubscriptionEvent {
77                tool_call_id, ..
78            }) => tool_call_id,
79            SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport { tool_call_id, .. }) => {
80                tool_call_id
81            }
82            SyntheticKind::Tagged(TaggedSyntheticKind::ParentMessage { tool_call_id }) => {
83                tool_call_id
84            }
85            SyntheticKind::Tagged(TaggedSyntheticKind::Compaction) => "",
86            SyntheticKind::Tagged(TaggedSyntheticKind::CompactionComplete) => "",
87            SyntheticKind::SubscriptionEvent(id) => id,
88        }
89    }
90
91    pub fn is_thread_report(&self) -> bool {
92        matches!(
93            self,
94            SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport { .. })
95        )
96    }
97
98    pub fn is_parent_message(&self) -> bool {
99        matches!(
100            self,
101            SyntheticKind::Tagged(TaggedSyntheticKind::ParentMessage { .. })
102        )
103    }
104
105    pub fn is_compaction(&self) -> bool {
106        matches!(self, SyntheticKind::Tagged(TaggedSyntheticKind::Compaction))
107    }
108
109    pub fn is_compaction_complete(&self) -> bool {
110        matches!(
111            self,
112            SyntheticKind::Tagged(TaggedSyntheticKind::CompactionComplete)
113        )
114    }
115
116    /// Associative subscription events are injected inline into the subscribing
117    /// thread's history (like thread reports) rather than spawning a child thread.
118    pub fn is_associative(&self) -> bool {
119        matches!(
120            self,
121            SyntheticKind::Tagged(TaggedSyntheticKind::SubscriptionEvent {
122                associative: true,
123                ..
124            })
125        )
126    }
127
128    /// When true, this is the final subscription event — the runtime should
129    /// remove the subscription from active tracking.
130    pub fn is_final(&self) -> bool {
131        matches!(
132            self,
133            SyntheticKind::Tagged(TaggedSyntheticKind::SubscriptionEvent { r#final: true, .. })
134        )
135    }
136}
137
138#[derive(Debug, Deserialize, Serialize, Clone)]
139pub struct InputMessage {
140    pub content: InputMessageContent,
141    pub group_id: ThreadId,
142    #[serde(default)]
143    pub metadata: Option<serde_json::Value>,
144    #[serde(default)]
145    pub synthetic: Option<SyntheticKind>,
146    /// Optional structured display segments for the CLI/UI. When present,
147    /// the UI shows these instead of the full tool result text. The model
148    /// still sees the full text.
149    #[serde(default)]
150    pub display_as: Option<Vec<rap_protocol::DisplaySegment>>,
151    /// When true, indicates this tool result started a subscription — the
152    /// runtime should track the tool call ID as an active subscription so
153    /// the agent can later cancel it via `cancel_subscription`.
154    #[serde(default)]
155    pub subscription: bool,
156}
157
158impl InputMessage {
159    /// A plain (non-synthetic) user text message addressed to `thread_id`.
160    pub fn user_text(thread_id: impl Into<ThreadId>, text: impl Into<String>) -> Self {
161        Self {
162            content: InputMessageContent::User(UserContent::text(text.into())),
163            group_id: thread_id.into(),
164            metadata: None,
165            synthetic: None,
166            display_as: None,
167            subscription: false,
168        }
169    }
170}
171
172/// Wraps message content with optional display metadata that survives
173/// serialization. On replay the display metadata is used directly instead of
174/// being reconstructed or stored as sidecar data.
175///
176/// Each variant stores the type-specific content struct directly rather than
177/// a full [`Message`]. Use [`into_messages`](Self::into_messages) to
178/// reconstruct the `Message`s for LLM calls.
179#[derive(Debug, Clone, Serialize, Deserialize)]
180#[serde(tag = "kind")]
181pub enum InfinityMessage {
182    /// Plain user text message.
183    #[serde(rename = "user")]
184    User { content: UserContent },
185    /// Assistant text or reasoning message.
186    #[serde(rename = "assistant")]
187    Assistant { content: AssistantContent },
188    /// Assistant tool call with optional pretty-printed display string.
189    #[serde(rename = "tool_call")]
190    ToolCall {
191        call: ToolCall,
192        #[serde(default, skip_serializing_if = "Option::is_none")]
193        display_as: Option<String>,
194    },
195    /// User tool result with optional display segments for the UI.
196    #[serde(rename = "tool_result")]
197    ToolResult {
198        result: ToolResult,
199        #[serde(default, skip_serializing_if = "Option::is_none")]
200        display_segments: Option<Vec<rap_protocol::DisplaySegment>>,
201    },
202    /// Synthetic subscription event injected into history. The display name is
203    /// recomputed on replay from the original tool call in history.
204    ///
205    /// The payloads are boxed to keep this rare variant from inflating the
206    /// size of every `InfinityMessage` (histories store many of these enums
207    /// inline). `Box` is transparent to serde, so the wire format is
208    /// unchanged.
209    #[serde(rename = "subscription_event")]
210    SubscriptionEvent {
211        result: Box<ToolResult>,
212        /// The tool_call_id of the original subscription tool call.
213        tool_call_id: String,
214        /// Set when this is a thread report (used to build the display name).
215        #[serde(default, skip_serializing_if = "Option::is_none")]
216        child_thread_id: Option<ThreadId>,
217        /// The synthetic `receive_event__injected` tool call. When present,
218        /// `into_messages` emits both the tool call and the tool result for
219        /// the LLM, but replay only emits the subscription display event.
220        /// `None` for backward-compat with old serialized histories.
221        #[serde(default, skip_serializing_if = "Option::is_none")]
222        invocation: Option<Box<ToolCall>>,
223    },
224}
225
226impl InfinityMessage {
227    /// Reconstruct [`Message`]s for LLM calls.
228    /// Most variants produce one message; `SubscriptionEvent` with an
229    /// `invocation` produces two (tool call + tool result).
230    pub fn into_messages(self) -> Vec<Message> {
231        match self {
232            Self::User { content } => vec![Message::User {
233                content: vec![content],
234            }],
235            Self::Assistant { content } => vec![Message::Assistant {
236                content: vec![content],
237            }],
238            Self::ToolCall { call, .. } => vec![Message::Assistant {
239                content: vec![AssistantContent::ToolCall(call)],
240            }],
241            Self::ToolResult { result, .. } => vec![Message::User {
242                content: vec![UserContent::ToolResult(result)],
243            }],
244            Self::SubscriptionEvent {
245                result, invocation, ..
246            } => {
247                let mut msgs = Vec::new();
248                if let Some(call) = invocation {
249                    msgs.push(Message::Assistant {
250                        content: vec![AssistantContent::ToolCall(*call)],
251                    });
252                }
253                msgs.push(Message::User {
254                    content: vec![UserContent::ToolResult(*result)],
255                });
256                msgs
257            }
258        }
259    }
260
261    /// The tool result carried by a `ToolResult` or `SubscriptionEvent`
262    /// message, if any.
263    pub fn tool_result(&self) -> Option<&ToolResult> {
264        match self {
265            Self::ToolResult { result, .. } => Some(result),
266            Self::SubscriptionEvent { result, .. } => Some(result),
267            _ => None,
268        }
269    }
270
271    /// Auto-classify a bare [`Message`] into the appropriate InfinityMessage
272    /// variant. Display metadata fields are set to `None`/defaults.
273    pub fn from_message(msg: Message) -> Self {
274        match msg {
275            Message::User { content } => {
276                let first = content.into_iter().next().expect("bug: empty content");
277                match first {
278                    UserContent::ToolResult(result) => Self::ToolResult {
279                        result,
280                        display_segments: None,
281                    },
282                    other => Self::User { content: other },
283                }
284            }
285            Message::Assistant { content } => {
286                let first = content.into_iter().next().expect("bug: empty content");
287                match first {
288                    AssistantContent::ToolCall(call) => Self::ToolCall {
289                        call,
290                        display_as: None,
291                    },
292                    other => Self::Assistant { content: other },
293                }
294            }
295        }
296    }
297}