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