Skip to main content

infinity_agent_core/
message.rs

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