Skip to main content

aidaemon_core/
message.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4/// Who authored a message in the transcript.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum Role {
8    System,
9    User,
10    Assistant,
11    Tool,
12}
13
14/// Who put a message into the transcript. Policies use this instead of
15/// matching text to tell real user input from harness feedback, and
16/// providers use it to tell a hook's per-request note from the transcript.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum MessageOrigin {
20    /// Typed by the user (or the calling application).
21    User,
22    /// Injected by the kernel, such as a stuck-detection nudge or an
23    /// `after_model` hook's reason for rejecting a response.
24    Harness,
25    /// Injected because an `on_stop` hook rejected a final answer.
26    StopHook,
27    /// A system note a `before_model` hook added to one model request (for
28    /// example recalled memory); it is not part of the run's transcript.
29    HookNote,
30}
31
32/// One tool invocation requested by the model.
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct ToolCall {
35    /// Provider-assigned id. The loop fills one in if the provider sent none.
36    pub id: String,
37    pub name: String,
38    /// Arguments as JSON. Providers that send a string should parse it first.
39    pub arguments: Value,
40    /// Opaque data the same provider needs back when this call is replayed
41    /// in a later request (a reasoning signature, thinking blocks). Other
42    /// providers ignore it.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub provider_data: Option<Value>,
45}
46
47impl ToolCall {
48    pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: Value) -> Self {
49        Self {
50            id: id.into(),
51            name: name.into(),
52            arguments,
53            provider_data: None,
54        }
55    }
56
57    pub fn with_provider_data(mut self, data: Value) -> Self {
58        self.provider_data = Some(data);
59        self
60    }
61}
62
63/// An image the model should look at. Carried on user messages and on tool
64/// results; providers map it to their own wire format and ignore it on other
65/// roles. `Debug` omits the encoded bytes so transcripts stay loggable.
66#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(tag = "source", rename_all = "snake_case")]
68pub enum Image {
69    /// Inline bytes, base64-encoded (standard alphabet, with padding).
70    Base64 { media_type: String, data: String },
71    /// A URL the provider fetches itself.
72    Url { url: String },
73}
74
75impl Image {
76    pub fn base64(media_type: impl Into<String>, data: impl Into<String>) -> Self {
77        Self::Base64 {
78            media_type: media_type.into(),
79            data: data.into(),
80        }
81    }
82
83    pub fn url(url: impl Into<String>) -> Self {
84        Self::Url { url: url.into() }
85    }
86
87    /// An image from a URL: a `data:<type>;base64,` URL becomes inline
88    /// bytes (providers that take no URLs can then still send it), anything
89    /// else stays a URL.
90    pub fn from_url_or_data(url: &str) -> Self {
91        url.strip_prefix("data:")
92            .and_then(|rest| rest.split_once(";base64,"))
93            .filter(|(media_type, data)| !media_type.is_empty() && !data.is_empty())
94            .map_or_else(
95                || Self::url(url),
96                |(media_type, data)| Self::base64(media_type, data),
97            )
98    }
99
100    /// The image as a URL: the URL itself, or a `data:` URL for inline bytes.
101    pub fn to_url(&self) -> String {
102        match self {
103            Self::Base64 { media_type, data } => format!("data:{media_type};base64,{data}"),
104            Self::Url { url } => url.clone(),
105        }
106    }
107}
108
109impl std::fmt::Debug for Image {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        match self {
112            Self::Base64 { media_type, data } => f
113                .debug_struct("Base64")
114                .field("media_type", media_type)
115                .field("bytes_b64", &data.len())
116                .finish(),
117            Self::Url { url } => f.debug_struct("Url").field("url", url).finish(),
118        }
119    }
120}
121
122/// Audio the model should hear, on a user message: base64 data in a
123/// container named the OpenAI way (`ogg`/`opus`, `mp3`, `wav`, `flac`,
124/// `aac`). Providers without audio input drop it. `Debug` omits the bytes.
125#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Audio {
127    pub format: String,
128    pub data: String,
129}
130
131impl Audio {
132    pub fn new(format: impl Into<String>, data: impl Into<String>) -> Self {
133        Self {
134            format: format.into(),
135            data: data.into(),
136        }
137    }
138
139    /// The MIME type for [`Audio::format`], when it is a known one.
140    pub fn media_type(&self) -> Option<&'static str> {
141        Some(match self.format.as_str() {
142            "ogg" | "opus" => "audio/ogg",
143            "mp3" => "audio/mp3",
144            "wav" => "audio/wav",
145            "flac" => "audio/flac",
146            "aac" => "audio/aac",
147            _ => return None,
148        })
149    }
150}
151
152impl std::fmt::Debug for Audio {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("Audio")
155            .field("format", &self.format)
156            .field("bytes_b64", &self.data.len())
157            .finish()
158    }
159}
160
161/// A provider-neutral transcript entry.
162///
163/// The transcript stored in [`crate::RunState`] never contains the agent's
164/// instructions; they are prepended on every request so they survive any
165/// future compaction and keep the cacheable prefix stable.
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
167pub struct Message {
168    pub role: Role,
169    pub content: String,
170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171    pub tool_calls: Vec<ToolCall>,
172    /// Set on `Role::Tool` messages: the call this result answers.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub tool_call_id: Option<String>,
175    /// Images on `Role::User` and `Role::Tool` messages, in order after the
176    /// text. Providers ignore them on other roles.
177    #[serde(default, skip_serializing_if = "Vec::is_empty")]
178    pub images: Vec<Image>,
179    /// Audio on `Role::User` messages. Providers ignore it on other roles.
180    #[serde(default, skip_serializing_if = "Vec::is_empty")]
181    pub audio: Vec<Audio>,
182    /// Set on `Role::Tool` messages whose receipt is not a success, so
183    /// providers can flag the result (for example Anthropic's `is_error`).
184    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
185    pub is_error: bool,
186    /// Who injected a `Role::User` message, or [`MessageOrigin::HookNote`]
187    /// on a hook's system note. `None` otherwise.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub origin: Option<MessageOrigin>,
190    /// The model's visible reasoning for this `Role::Assistant` turn, kept
191    /// for the transcript. Providers do not send it back: what a provider
192    /// must replay (Anthropic's signed thinking) rides on
193    /// [`ToolCall::provider_data`].
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub reasoning: Option<String>,
196    /// Who typed a `Role::User` message, when the application tells people
197    /// apart (a group chat's participants). `None` when it does not: a
198    /// one-person conversation, or history stored before senders were
199    /// recorded. The untrusted-content rule counts a string as the user's
200    /// only when the run's latest request and the message naming it share a
201    /// sender (see [`crate::UntrustedHook`]).
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub sender: Option<String>,
204}
205
206impl Message {
207    pub fn system(content: impl Into<String>) -> Self {
208        Self::plain(Role::System, content)
209    }
210
211    pub fn user(content: impl Into<String>) -> Self {
212        Self::from_origin(MessageOrigin::User, content)
213    }
214
215    /// A user-role message injected by the harness or a hook.
216    pub fn from_origin(origin: MessageOrigin, content: impl Into<String>) -> Self {
217        let mut message = Self::plain(Role::User, content);
218        message.origin = Some(origin);
219        message
220    }
221
222    /// A system note a `before_model` hook adds to one request. Providers
223    /// that place notes apart from the transcript find them by this origin.
224    pub fn hook_note(content: impl Into<String>) -> Self {
225        let mut message = Self::plain(Role::System, content);
226        message.origin = Some(MessageOrigin::HookNote);
227        message
228    }
229
230    /// True for a [`Message::hook_note`].
231    pub fn is_hook_note(&self) -> bool {
232        self.origin == Some(MessageOrigin::HookNote)
233    }
234
235    /// True for user-role messages the harness or a hook injected.
236    pub fn is_injected(&self) -> bool {
237        matches!(
238            self.origin,
239            Some(MessageOrigin::Harness | MessageOrigin::StopHook)
240        )
241    }
242
243    pub fn assistant(content: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
244        Self {
245            role: Role::Assistant,
246            content: content.into(),
247            tool_calls,
248            tool_call_id: None,
249            images: Vec::new(),
250            audio: Vec::new(),
251            is_error: false,
252            origin: None,
253            reasoning: None,
254            sender: None,
255        }
256    }
257
258    pub fn tool_result(call_id: impl Into<String>, content: impl Into<String>) -> Self {
259        Self {
260            role: Role::Tool,
261            content: content.into(),
262            tool_calls: Vec::new(),
263            tool_call_id: Some(call_id.into()),
264            images: Vec::new(),
265            audio: Vec::new(),
266            is_error: false,
267            origin: None,
268            reasoning: None,
269            sender: None,
270        }
271    }
272
273    /// Attach images (see [`Image`]).
274    pub fn with_images(mut self, images: impl IntoIterator<Item = Image>) -> Self {
275        self.images.extend(images);
276        self
277    }
278
279    /// Attach audio (see [`Audio`]).
280    pub fn with_audio(mut self, audio: impl IntoIterator<Item = Audio>) -> Self {
281        self.audio.extend(audio);
282        self
283    }
284
285    /// Mark a tool result as an error.
286    pub fn with_reasoning(mut self, reasoning: Option<String>) -> Self {
287        self.reasoning = reasoning;
288        self
289    }
290
291    /// Attribute a user message to the person who typed it (see
292    /// [`Message::sender`]).
293    pub fn with_sender(mut self, sender: impl Into<String>) -> Self {
294        self.sender = Some(sender.into());
295        self
296    }
297
298    pub fn with_error(mut self, is_error: bool) -> Self {
299        self.is_error = is_error;
300        self
301    }
302
303    fn plain(role: Role, content: impl Into<String>) -> Self {
304        Self {
305            role,
306            content: content.into(),
307            tool_calls: Vec::new(),
308            tool_call_id: None,
309            images: Vec::new(),
310            audio: Vec::new(),
311            is_error: false,
312            origin: None,
313            reasoning: None,
314            sender: None,
315        }
316    }
317}
318
319/// Plain text becomes a user message, so `Agent::run` and
320/// `RunState::with_user_message` take either text or a built [`Message`]
321/// (for example one with images).
322impl From<&str> for Message {
323    fn from(text: &str) -> Self {
324        Self::user(text)
325    }
326}
327
328impl From<&String> for Message {
329    fn from(text: &String) -> Self {
330        Self::user(text.as_str())
331    }
332}
333
334impl From<String> for Message {
335    fn from(text: String) -> Self {
336        Self::user(text)
337    }
338}