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}
197
198impl Message {
199    pub fn system(content: impl Into<String>) -> Self {
200        Self::plain(Role::System, content)
201    }
202
203    pub fn user(content: impl Into<String>) -> Self {
204        Self::from_origin(MessageOrigin::User, content)
205    }
206
207    /// A user-role message injected by the harness or a hook.
208    pub fn from_origin(origin: MessageOrigin, content: impl Into<String>) -> Self {
209        let mut message = Self::plain(Role::User, content);
210        message.origin = Some(origin);
211        message
212    }
213
214    /// A system note a `before_model` hook adds to one request. Providers
215    /// that place notes apart from the transcript find them by this origin.
216    pub fn hook_note(content: impl Into<String>) -> Self {
217        let mut message = Self::plain(Role::System, content);
218        message.origin = Some(MessageOrigin::HookNote);
219        message
220    }
221
222    /// True for a [`Message::hook_note`].
223    pub fn is_hook_note(&self) -> bool {
224        self.origin == Some(MessageOrigin::HookNote)
225    }
226
227    /// True for user-role messages the harness or a hook injected.
228    pub fn is_injected(&self) -> bool {
229        matches!(
230            self.origin,
231            Some(MessageOrigin::Harness | MessageOrigin::StopHook)
232        )
233    }
234
235    pub fn assistant(content: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
236        Self {
237            role: Role::Assistant,
238            content: content.into(),
239            tool_calls,
240            tool_call_id: None,
241            images: Vec::new(),
242            audio: Vec::new(),
243            is_error: false,
244            origin: None,
245            reasoning: None,
246        }
247    }
248
249    pub fn tool_result(call_id: impl Into<String>, content: impl Into<String>) -> Self {
250        Self {
251            role: Role::Tool,
252            content: content.into(),
253            tool_calls: Vec::new(),
254            tool_call_id: Some(call_id.into()),
255            images: Vec::new(),
256            audio: Vec::new(),
257            is_error: false,
258            origin: None,
259            reasoning: None,
260        }
261    }
262
263    /// Attach images (see [`Image`]).
264    pub fn with_images(mut self, images: impl IntoIterator<Item = Image>) -> Self {
265        self.images.extend(images);
266        self
267    }
268
269    /// Attach audio (see [`Audio`]).
270    pub fn with_audio(mut self, audio: impl IntoIterator<Item = Audio>) -> Self {
271        self.audio.extend(audio);
272        self
273    }
274
275    /// Mark a tool result as an error.
276    pub fn with_reasoning(mut self, reasoning: Option<String>) -> Self {
277        self.reasoning = reasoning;
278        self
279    }
280
281    pub fn with_error(mut self, is_error: bool) -> Self {
282        self.is_error = is_error;
283        self
284    }
285
286    fn plain(role: Role, content: impl Into<String>) -> Self {
287        Self {
288            role,
289            content: content.into(),
290            tool_calls: Vec::new(),
291            tool_call_id: None,
292            images: Vec::new(),
293            audio: Vec::new(),
294            is_error: false,
295            origin: None,
296            reasoning: None,
297        }
298    }
299}
300
301/// Plain text becomes a user message, so `Agent::run` and
302/// `RunState::with_user_message` take either text or a built [`Message`]
303/// (for example one with images).
304impl From<&str> for Message {
305    fn from(text: &str) -> Self {
306        Self::user(text)
307    }
308}
309
310impl From<&String> for Message {
311    fn from(text: &String) -> Self {
312        Self::user(text.as_str())
313    }
314}
315
316impl From<String> for Message {
317    fn from(text: String) -> Self {
318        Self::user(text)
319    }
320}