trusty_code/llm/message.rs
1//! `ChatMessage` wire type and role constructors.
2//!
3//! Why: The conversation-message type is used by both requests (history) and
4//! tool-result injection; isolating it here keeps the request and response
5//! modules free of message construction boilerplate.
6//! What: Defines `ChatMessage` with `role`, `content`, `tool_calls`,
7//! `tool_call_id`, `name`, and (#2156) `cache_control` fields, plus convenience
8//! constructors for each standard role.
9//! Test: `chat_message_constructors`, `chat_message_tool_role_round_trip`,
10//! `chat_message_serialises_all_roles`,
11//! `chat_message_cache_control_serialises_as_content_block`,
12//! `chat_message_without_cache_control_serialises_plain_string`.
13
14use serde::ser::SerializeStruct;
15use serde::{Deserialize, Serialize, Serializer};
16
17use super::request::{CacheControl, ToolCall};
18
19/// A single message in the chat conversation.
20///
21/// Why: OpenRouter's `/chat/completions` endpoint uses the standard OpenAI
22/// message schema; `role` distinguishes speaker identity and `content` carries
23/// the text payload (or `null` for tool-call-only turns).
24/// What: `role` is one of `"system"`, `"user"`, `"assistant"`, `"tool"`;
25/// `content` is the text or `None` for assistant turns that only emit tool
26/// calls; `tool_calls` carries the outbound calls for assistant turns;
27/// `tool_call_id` and `name` are populated for `tool` role messages;
28/// `cache_control` (#2156) is a prompt-cache breakpoint applied at
29/// serialisation time — see [`Self::serialize`] for the wire-shape switch it
30/// drives.
31/// Test: `chat_message_serialises_all_roles`.
32#[derive(Debug, Clone, Deserialize, PartialEq)]
33pub struct ChatMessage {
34 /// Conversation role: `"system"`, `"user"`, `"assistant"`, or `"tool"`.
35 pub role: String,
36
37 /// Text content; `None` on assistant turns that only emit tool calls.
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub content: Option<String>,
40
41 /// Tool calls emitted by the assistant.
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub tool_calls: Option<Vec<ToolCall>>,
44
45 /// For `tool` role messages: the ID of the tool call this message responds to.
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub tool_call_id: Option<String>,
48
49 /// For `tool` role messages: the name of the function that was called.
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub name: Option<String>,
52
53 /// Prompt-cache breakpoint (#2156). Never read back from the wire (this
54 /// type is request-only — see the module doc), so it is dropped on
55 /// deserialise via `#[serde(skip)]` rather than round-tripped.
56 /// `agent_loop::build_request` sets this on the system-role message when
57 /// the run is cache-eligible; see [`Self::serialize`] for how it changes
58 /// `content`'s wire shape.
59 #[serde(skip)]
60 pub cache_control: Option<CacheControl>,
61}
62
63impl Serialize for ChatMessage {
64 /// Serialise `ChatMessage`, converting `content` into a one-element
65 /// cache-annotated content-block array when `cache_control` is set
66 /// (#2156), and a bare string (today's shape) otherwise.
67 ///
68 /// Why: OpenRouter's Claude `cache_control` passthrough only honours the
69 /// breakpoint when `content` is shaped as
70 /// `[{"type":"text","text":...,"cache_control":{"type":"ephemeral"}}]` —
71 /// a plain string `content` value is never inspected for a cache marker
72 /// (verified against OpenRouter's prompt-caching docs and `block/goose`'s
73 /// production OpenRouter provider). Hand-writing this impl — rather than
74 /// deriving — keeps `content: Option<String>` the type every other call
75 /// site (`Transcript`, tests) already depends on; only the wire encoding
76 /// branches on `cache_control`.
77 /// What: `role` always serialises. `content` serialises as the cached
78 /// block array when both `content` and `cache_control` are `Some`, as a
79 /// bare string when only `content` is `Some`, and is omitted entirely
80 /// when `content` is `None` — matching the previous
81 /// `skip_serializing_if = "Option::is_none"` behaviour byte-for-byte when
82 /// `cache_control` is `None`. `tool_calls`, `tool_call_id`, and `name`
83 /// serialise unchanged; `cache_control` itself never appears as its own
84 /// JSON key.
85 /// Test: `chat_message_cache_control_serialises_as_content_block`,
86 /// `chat_message_without_cache_control_serialises_plain_string`,
87 /// `chat_message_serialises_all_roles`.
88 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
89 where
90 S: Serializer,
91 {
92 let mut state = serializer.serialize_struct("ChatMessage", 5)?;
93 state.serialize_field("role", &self.role)?;
94
95 match (&self.content, &self.cache_control) {
96 (Some(text), Some(cache_control)) => {
97 let block = [CachedTextBlock {
98 kind: "text",
99 text: text.as_str(),
100 cache_control,
101 }];
102 state.serialize_field("content", &block)?;
103 }
104 (Some(text), None) => state.serialize_field("content", text)?,
105 (None, _) => state.skip_field("content")?,
106 }
107
108 match &self.tool_calls {
109 Some(calls) => state.serialize_field("tool_calls", calls)?,
110 None => state.skip_field("tool_calls")?,
111 }
112 match &self.tool_call_id {
113 Some(id) => state.serialize_field("tool_call_id", id)?,
114 None => state.skip_field("tool_call_id")?,
115 }
116 match &self.name {
117 Some(name) => state.serialize_field("name", name)?,
118 None => state.skip_field("name")?,
119 }
120
121 state.end()
122 }
123}
124
125/// Wire shape for one Anthropic-ephemeral cached text content block (#2156).
126///
127/// Why: `[{"type":"text","text":...,"cache_control":{"type":"ephemeral"}}]`
128/// is exactly OpenRouter's documented Claude `cache_control` passthrough
129/// shape for message content; this private struct is the single place that
130/// shape is expressed instead of building it ad hoc inside
131/// `ChatMessage::serialize`.
132/// What: `kind` is always `"text"`; `text`/`cache_control` borrow from the
133/// owning `ChatMessage` to avoid a clone during serialisation.
134/// Test: exercised indirectly via
135/// `chat_message_cache_control_serialises_as_content_block`.
136#[derive(Serialize)]
137struct CachedTextBlock<'a> {
138 #[serde(rename = "type")]
139 kind: &'static str,
140 text: &'a str,
141 cache_control: &'a CacheControl,
142}
143
144impl ChatMessage {
145 /// Construct a `system` message.
146 ///
147 /// Why: Convenience constructor; avoids repeated `role.to_string()` boilerplate.
148 /// What: Returns a `ChatMessage` with `role = "system"` and the provided content.
149 /// Test: `chat_message_constructors`.
150 pub fn system(content: impl Into<String>) -> Self {
151 Self {
152 role: "system".into(),
153 content: Some(content.into()),
154 tool_calls: None,
155 tool_call_id: None,
156 name: None,
157 cache_control: None,
158 }
159 }
160
161 /// Construct a `user` message.
162 ///
163 /// Why: Convenience constructor for the most common message type.
164 /// What: Returns a `ChatMessage` with `role = "user"` and the provided content.
165 /// Test: `chat_message_constructors`.
166 pub fn user(content: impl Into<String>) -> Self {
167 Self {
168 role: "user".into(),
169 content: Some(content.into()),
170 tool_calls: None,
171 tool_call_id: None,
172 name: None,
173 cache_control: None,
174 }
175 }
176
177 /// Construct an `assistant` message with text content.
178 ///
179 /// Why: Convenience constructor for building conversation history from prior
180 /// assistant responses.
181 /// What: Returns a `ChatMessage` with `role = "assistant"` and the provided content.
182 /// Test: `chat_message_constructors`.
183 pub fn assistant(content: impl Into<String>) -> Self {
184 Self {
185 role: "assistant".into(),
186 content: Some(content.into()),
187 tool_calls: None,
188 tool_call_id: None,
189 name: None,
190 cache_control: None,
191 }
192 }
193
194 /// Construct a `tool` result message.
195 ///
196 /// Why: After executing a tool call, the result must be fed back in a `tool`
197 /// role message referencing the original `tool_call_id`.
198 /// What: Returns a `ChatMessage` with `role = "tool"`, the call ID, function
199 /// name, and result content.
200 /// Test: `chat_message_tool_role_round_trip`.
201 pub fn tool_result(
202 tool_call_id: impl Into<String>,
203 name: impl Into<String>,
204 content: impl Into<String>,
205 ) -> Self {
206 Self {
207 role: "tool".into(),
208 content: Some(content.into()),
209 tool_calls: None,
210 tool_call_id: Some(tool_call_id.into()),
211 name: Some(name.into()),
212 cache_control: None,
213 }
214 }
215}
216
217// ── Tests ─────────────────────────────────────────────────────────────────────
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 /// Convenience constructors produce the right `role` strings.
224 ///
225 /// Why: Verify each static constructor sets the role correctly.
226 /// What: Assert roles for `system`, `user`, `assistant`.
227 /// Test: this test.
228 #[test]
229 fn chat_message_constructors() {
230 assert_eq!(ChatMessage::system("s").role, "system");
231 assert_eq!(ChatMessage::user("u").role, "user");
232 assert_eq!(ChatMessage::assistant("a").role, "assistant");
233 }
234
235 /// `tool_result` constructor sets `tool_call_id` and `name`.
236 ///
237 /// Why: Tool result messages have extra required fields; the constructor must
238 /// populate them correctly.
239 /// What: Assert `tool_call_id` and `name` are `Some`.
240 /// Test: this test.
241 #[test]
242 fn chat_message_tool_role_round_trip() {
243 let msg = ChatMessage::tool_result("call_abc", "get_weather", r#"{"temp":72}"#);
244 assert_eq!(msg.role, "tool");
245 assert_eq!(msg.tool_call_id.as_deref(), Some("call_abc"));
246 assert_eq!(msg.name.as_deref(), Some("get_weather"));
247 assert_eq!(msg.content.as_deref(), Some(r#"{"temp":72}"#));
248 }
249
250 /// All role constructors serialise the `role` field correctly.
251 ///
252 /// Why: JSON consumers depend on the `role` string value; a typo in any
253 /// constructor would silently break the API.
254 /// What: Serialise each message variant, assert the `role` JSON field value.
255 /// Test: this test.
256 #[test]
257 fn chat_message_serialises_all_roles() {
258 for (msg, expected_role) in [
259 (ChatMessage::system("sys"), "system"),
260 (ChatMessage::user("usr"), "user"),
261 (ChatMessage::assistant("ast"), "assistant"),
262 (ChatMessage::tool_result("id", "fn", "result"), "tool"),
263 ] {
264 let v: serde_json::Value = serde_json::to_value(&msg).expect("serialise");
265 assert_eq!(
266 v["role"].as_str(),
267 Some(expected_role),
268 "role mismatch for expected={expected_role}"
269 );
270 }
271 }
272
273 /// A message with `cache_control` set serialises `content` as a
274 /// one-element cache-annotated block array (#2156).
275 ///
276 /// Why: This is the exact shape OpenRouter's Claude passthrough requires
277 /// to honour the breakpoint; a plain-string `content` would be silently
278 /// ignored by Anthropic's caching layer.
279 /// What: Build a system message, set `cache_control`, serialise, assert
280 /// `content` is `[{"type":"text","text":...,"cache_control":
281 /// {"type":"ephemeral"}}]`.
282 /// Test: this test.
283 #[test]
284 fn chat_message_cache_control_serialises_as_content_block() {
285 let mut msg = ChatMessage::system("you are helpful");
286 msg.cache_control = Some(CacheControl::ephemeral());
287
288 let v: serde_json::Value = serde_json::to_value(&msg).expect("serialise");
289 assert_eq!(
290 v["content"],
291 serde_json::json!([{
292 "type": "text",
293 "text": "you are helpful",
294 "cache_control": {"type": "ephemeral"}
295 }])
296 );
297 assert_eq!(v["role"], "system");
298 }
299
300 /// A message WITHOUT `cache_control` serialises `content` as a bare
301 /// string — byte-identical to pre-#2156 output (#2156 regression guard).
302 ///
303 /// Why: Every non-caching request (Parity mode, non-Anthropic models)
304 /// must be unaffected by this change; this pins that the default
305 /// (`cache_control: None`) path never emits the block-array shape.
306 /// What: Build a system message via the ordinary constructor (leaving
307 /// `cache_control` at its default `None`), serialise, assert `content`
308 /// is the plain string.
309 /// Test: this test.
310 #[test]
311 fn chat_message_without_cache_control_serialises_plain_string() {
312 let msg = ChatMessage::system("you are helpful");
313 assert!(msg.cache_control.is_none());
314
315 let v: serde_json::Value = serde_json::to_value(&msg).expect("serialise");
316 assert_eq!(v["content"], serde_json::json!("you are helpful"));
317 }
318}