返回 CodeWhale
role_placement.rs
根目录 / crates / engine / src / client / role_placement.rs
1 //! The one table that answers "where does a message with this role go on this
2 //! wire, and when is the pair not representable at all?"
3 //!
4 //! Before this module existed the question was answered once per adapter, and
5 //! the answers disagreed — not by design, by drift:
6 //!
7 //! * Chat Completions matched `user`/`assistant`/`system` and let anything
8 //! else fall off the end of an `if`/`else if` chain, silently.
9 //! * OpenAI Responses matched `user`/`assistant`/`tool` and swallowed
10 //! `system` in a catch-all `_ => {}`.
11 //! * Anthropic Messages forwarded `message.role` **verbatim**, so a `system`
12 //! message earned an opaque provider-side 400 that named neither the role
13 //! nor the message.
14 //!
15 //! Now each adapter asks [`role_placement`] which channel to render into, and
16 //! [`reject_unsupported_roles`] runs at the outbound seam
17 //! (`CodewhaleClient::prepare_outbound_request`) so an unrepresentable pair is
18 //! refused locally, before any transport serialization, instead of being
19 //! discovered by the provider.
20 //!
21 //! Two rules govern edits here:
22 //!
23 //! * A role is **omitted** only where dropping it was already the behaviour
24 //! and the content is not load-bearing. Turning a hard error into a silent
25 //! drop is a fail-open regression, not a cleanup.
26 //! * Placement grants no authority. It says which wire channel carries the
27 //! bytes, never how much the model should trust them.
28
29 use super::prepared::WireDialect;
30 use codewhale_models::{Message, Role};
31
32 /// Which channel of a wire body a message renders into.
33 ///
34 /// Adapters own the structural rendering for their own dialect — Chat's
35 /// `tool_calls` array, Responses' `function_call_output` items, and Anthropic's
36 /// content blocks. This enum only names the channel, so
37 /// that the *choice* of channel is made in exactly one place.
38 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
39 pub enum RolePlacement {
40 /// The wire's user/input channel.
41 User,
42 /// The wire's assistant/model output channel.
43 Assistant,
44 /// The assistant channel, with the interrupted-output prefix prepended to
45 /// the replayed text so the model can see the turn was cut short.
46 InterruptedAssistant,
47 LatestReminder,
48 /// A system-role entry inside the transcript body (not the top-level
49 /// system prompt, which every dialect carries separately).
50 System,
51 /// A developer-role entry inside the transcript body.
52 Developer,
53 /// Not representable on this wire, and dropped rather than sent. Every
54 /// `Omitted` cell below is behaviour that already shipped.
55 Omitted,
56 /// Not representable and not safe to drop. The outbound seam refuses the
57 /// request; adapters treat it as unreachable and fail closed if reached.
58 Rejected,
59 }
60
61 impl RolePlacement {
62 /// True when the message renders into the assistant channel, interrupted
63 /// replay included.
64 pub fn is_assistant_channel(self) -> bool {
65 matches!(self, Self::Assistant | Self::InterruptedAssistant)
66 }
67 }
68
69 /// The placement table.
70 ///
71 /// Read the cells as the current, audited behaviour of each adapter. The two
72 /// cells that deliberately changed are marked; see the commit that introduced
73 /// this module.
74 pub fn role_placement(role: &Role, dialect: WireDialect) -> RolePlacement {
75 match (role, dialect) {
76 // Every dialect carries user input.
77 (Role::User, _) => RolePlacement::User,
78
79 // Every dialect carries assistant output.
80 (Role::Assistant, _) => RolePlacement::Assistant,
81
82 // Interrupted assistant text replays as assistant output with a marker.
83 (Role::InterruptedAssistant, _) => RolePlacement::InterruptedAssistant,
84
85 // Chat Completions and Responses both accept load-bearing system and
86 // developer entries inside transcript history. Anthropic accepts only
87 // user/assistant message roles, so it preserves the positioned content
88 // by projecting those entries onto the user channel. Hoisting them to
89 // the top-level system field or dropping them would reorder or delete
90 // compaction and branch summaries.
91 (Role::System, WireDialect::ChatCompletions | WireDialect::OpenAiResponses) => {
92 RolePlacement::System
93 }
94 (Role::System, WireDialect::AnthropicMessages | WireDialect::GenerateContent) => {
95 RolePlacement::User
96 }
97
98 (Role::Developer, WireDialect::ChatCompletions | WireDialect::OpenAiResponses) => {
99 RolePlacement::Developer
100 }
101 (Role::Developer, WireDialect::AnthropicMessages | WireDialect::GenerateContent) => {
102 RolePlacement::User
103 }
104
105 (
106 Role::LatestReminder,
107 WireDialect::ChatCompletions
108 | WireDialect::AnthropicMessages
109 | WireDialect::GenerateContent,
110 ) => RolePlacement::LatestReminder,
111 (Role::LatestReminder, WireDialect::OpenAiResponses) => RolePlacement::Rejected,
112
113 // A role this build does not know, e.g. from a transcript written by
114 // a newer build. The OpenAI-shaped dialects already dropped these;
115 // Anthropic sent them verbatim for the provider to reject.
116 (
117 Role::Unrecognized(_),
118 WireDialect::ChatCompletions
119 | WireDialect::OpenAiResponses
120 | WireDialect::GenerateContent,
121 ) => RolePlacement::Omitted,
122 // CHANGED: was a verbatim pass-through ending in a provider 400.
123 (Role::Unrecognized(_), WireDialect::AnthropicMessages) => RolePlacement::Rejected,
124 }
125 }
126
127 /// A role/dialect pair this build refuses to put on the wire.
128 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
129 #[error(
130 "message {index} has role {role:?}, which the {dialect} wire cannot represent; \
131 the request was refused before it was sent"
132 )]
133 pub struct UnsupportedRoleForDialect {
134 /// Index of the offending message in the outbound transcript.
135 pub index: usize,
136 /// The role as it appears in the transcript.
137 pub role: String,
138 /// Stable machine label for the wire dialect.
139 pub dialect: &'static str,
140 }
141
142 /// Refuse an outbound transcript that a dialect cannot represent.
143 ///
144 /// This is the validation seam: it runs inside
145 /// `CodewhaleClient::prepare_outbound_request`, before any dialect builds a
146 /// body, so no rejected pair ever reaches transport serialization.
147 pub fn reject_unsupported_roles(
148 messages: &[Message],
149 dialect: WireDialect,
150 ) -> Result<(), UnsupportedRoleForDialect> {
151 for (index, message) in messages.iter().enumerate() {
152 if role_placement(&message.role, dialect) == RolePlacement::Rejected {
153 return Err(UnsupportedRoleForDialect {
154 index,
155 role: message.role.to_string(),
156 dialect: dialect.as_str(),
157 });
158 }
159 }
160 Ok(())
161 }
162
163 pub fn validate_latest_reminder_messages(messages: &[Message]) -> anyhow::Result<()> {
164 for (index, message) in messages.iter().enumerate() {
165 if message.role != Role::LatestReminder {
166 continue;
167 }
168 let mut has_text = false;
169 for block in &message.content {
170 match block {
171 codewhale_models::ContentBlock::Text { text, .. } => {
172 if !text.trim().is_empty() {
173 has_text = true;
174 }
175 }
176 _ => anyhow::bail!(
177 "latest_reminder message at index {index} must contain text content only"
178 ),
179 }
180 }
181 if !has_text {
182 anyhow::bail!("latest_reminder message at index {index} must contain string content");
183 }
184 let Some(next) = messages.get(index + 1) else {
185 anyhow::bail!(
186 "latest_reminder message at index {index} must be placed directly before a user message"
187 );
188 };
189 if next.role != Role::User {
190 anyhow::bail!(
191 "latest_reminder message at index {index} must be placed directly before a user message"
192 );
193 }
194 if next
195 .content
196 .iter()
197 .any(|block| matches!(block, codewhale_models::ContentBlock::ToolResult { .. }))
198 {
199 anyhow::bail!(
200 "latest_reminder message at index {index} cannot be placed before a tool_result message"
201 );
202 }
203 if index > 0
204 && messages[index - 1].role.is_assistant_like()
205 && messages[index - 1]
206 .content
207 .iter()
208 .any(|block| matches!(block, codewhale_models::ContentBlock::ToolUse { .. }))
209 {
210 anyhow::bail!(
211 "latest_reminder message at index {index} cannot be placed between tool_use and tool_result"
212 );
213 }
214 }
215 Ok(())
216 }
217
218 #[cfg(test)]
219 mod tests {
220 use super::{RolePlacement, WireDialect, reject_unsupported_roles, role_placement};
221 use codewhale_models::{ContentBlock, Message, Role};
222
223 const DIALECTS: [WireDialect; 3] = [
224 WireDialect::ChatCompletions,
225 WireDialect::AnthropicMessages,
226 WireDialect::OpenAiResponses,
227 ];
228
229 fn message(role: Role) -> Message {
230 Message {
231 role,
232 content: vec![ContentBlock::Text {
233 text: "body".to_string(),
234 cache_control: None,
235 }],
236 }
237 }
238
239 #[test]
240 fn user_and_assistant_are_carried_by_every_dialect() {
241 for dialect in DIALECTS {
242 assert_eq!(role_placement(&Role::User, dialect), RolePlacement::User);
243 assert_eq!(
244 role_placement(&Role::Assistant, dialect),
245 RolePlacement::Assistant
246 );
247 }
248 }
249
250 #[test]
251 fn interrupted_assistant_replays_on_every_supported_dialect() {
252 for dialect in [
253 WireDialect::ChatCompletions,
254 WireDialect::AnthropicMessages,
255 WireDialect::OpenAiResponses,
256 ] {
257 let placement = role_placement(&Role::InterruptedAssistant, dialect);
258 assert_eq!(placement, RolePlacement::InterruptedAssistant);
259 assert!(placement.is_assistant_channel());
260 }
261 }
262
263 #[test]
264 fn positioned_instruction_roles_are_preserved_where_each_dialect_can_carry_them() {
265 assert_eq!(
266 role_placement(&Role::System, WireDialect::ChatCompletions),
267 RolePlacement::System
268 );
269 assert_eq!(
270 role_placement(&Role::System, WireDialect::OpenAiResponses),
271 RolePlacement::System
272 );
273 assert_eq!(
274 role_placement(&Role::System, WireDialect::AnthropicMessages),
275 RolePlacement::User
276 );
277 assert_eq!(
278 role_placement(&Role::Developer, WireDialect::ChatCompletions),
279 RolePlacement::Developer
280 );
281 assert_eq!(
282 role_placement(&Role::Developer, WireDialect::OpenAiResponses),
283 RolePlacement::Developer
284 );
285 assert_eq!(
286 role_placement(&Role::Developer, WireDialect::AnthropicMessages),
287 RolePlacement::User
288 );
289 }
290
291 #[test]
292 fn unknown_roles_never_reach_a_wire() {
293 let role = Role::Unrecognized("future_role".to_string());
294 for dialect in DIALECTS {
295 assert_ne!(
296 role_placement(&role, dialect),
297 RolePlacement::User,
298 "{} must not promote an unknown role",
299 dialect.as_str()
300 );
301 assert!(matches!(
302 role_placement(&role, dialect),
303 RolePlacement::Omitted | RolePlacement::Rejected
304 ));
305 }
306 }
307
308 #[test]
309 fn seam_accepts_positioned_system_history_on_anthropic() {
310 let messages = vec![
311 message(Role::User),
312 message(Role::Assistant),
313 message(Role::System),
314 ];
315 reject_unsupported_roles(&messages, WireDialect::AnthropicMessages)
316 .expect("Anthropic projects positioned system history onto the user channel");
317 }
318
319 #[test]
320 fn seam_accepts_what_each_dialect_can_carry() {
321 let plain = vec![message(Role::User), message(Role::Assistant)];
322 for dialect in DIALECTS {
323 assert!(reject_unsupported_roles(&plain, dialect).is_ok());
324 }
325 // Omitted is not rejected: genuinely unknown roles keep the legacy
326 // OpenAI-shaped behavior rather than failing a live session.
327 assert!(
328 reject_unsupported_roles(
329 &[
330 message(Role::System),
331 message(Role::Developer),
332 message(Role::Unrecognized("x".into()))
333 ],
334 WireDialect::OpenAiResponses,
335 )
336 .is_ok()
337 );
338 assert!(
339 reject_unsupported_roles(
340 &[message(Role::Unrecognized("x".into()))],
341 WireDialect::ChatCompletions,
342 )
343 .is_ok()
344 );
345 }
346 }
347
348 /// Each adapter, run over the same transcript, must land where the table says.
349 ///
350 /// These tests exist because the four adapters used to disagree with each
351 /// other and nothing noticed. They assert the *observable wire shape*, not the
352 /// table — a future edit that keeps the table honest but forgets to rewire an
353 /// adapter fails here.
354 #[cfg(test)]
355 mod adapter_agreement_tests {
356 use serde_json::{Value, json};
357
358 use super::super::{anthropic, chat, responses};
359 use codewhale_config::ProviderKind;
360 use codewhale_models::{
361 ContentBlock, INTERRUPTED_ASSISTANT_CONTEXT_PREFIX, Message, MessageRequest, Role,
362 };
363
364 fn message(role: Role, text: &str) -> Message {
365 Message {
366 role,
367 content: vec![ContentBlock::Text {
368 text: text.to_string(),
369 cache_control: None,
370 }],
371 }
372 }
373
374 fn request(messages: Vec<Message>) -> MessageRequest {
375 MessageRequest {
376 model: "test-model".to_string(),
377 messages,
378 max_tokens: 256,
379 system: None,
380 tools: None,
381 tool_choice: None,
382 metadata: None,
383 thinking: None,
384 reasoning_effort: None,
385 stream: Some(false),
386 temperature: None,
387 top_p: None,
388 safety_check: None,
389 title: None,
390 }
391 }
392
393 fn roles(items: &[Value]) -> Vec<String> {
394 items
395 .iter()
396 .filter_map(|item| item.get("role").and_then(Value::as_str))
397 .map(str::to_string)
398 .collect()
399 }
400
401 fn transcript() -> Vec<Message> {
402 vec![
403 message(Role::User, "ask"),
404 message(Role::Assistant, "answer"),
405 message(Role::InterruptedAssistant, "half an answer"),
406 message(Role::System, "compaction summary"),
407 message(Role::Developer, "developer instruction"),
408 message(Role::Unrecognized("future_role".to_string()), "from later"),
409 ]
410 }
411
412 #[test]
413 fn chat_completions_maps_every_role_the_table_says_it_can_carry() {
414 let items = chat::build_chat_messages_for_request_and_provider(
415 &request(transcript()),
416 ProviderKind::Deepseek,
417 );
418 assert_eq!(
419 roles(&items),
420 vec!["user", "assistant", "assistant", "system", "developer"],
421 "one wire entry per carried message, in transcript order: the \
422 interrupted turn joins the assistant channel; positioned system \
423 and developer history survive; the unknown role is dropped",
424 );
425 let rendered = serde_json::to_string(&items).expect("serialize");
426 assert!(
427 !rendered.contains("from later"),
428 "an unknown role must not reach the wire: {rendered}"
429 );
430 assert!(rendered.contains("compaction summary"));
431 assert!(rendered.contains("developer instruction"));
432 }
433
434 #[test]
435 fn chat_completions_marks_interrupted_assistant_history() {
436 let items = chat::build_chat_messages_for_request_and_provider(
437 &request(vec![message(Role::InterruptedAssistant, "half an answer")]),
438 ProviderKind::Deepseek,
439 );
440 assert_eq!(items.len(), 1);
441 assert_eq!(items[0]["role"], json!("assistant"));
442 assert_eq!(
443 items[0]["content"].as_str().expect("text content"),
444 format!("{INTERRUPTED_ASSISTANT_CONTEXT_PREFIX}half an answer"),
445 );
446 }
447
448 #[test]
449 fn responses_preserves_positioned_instruction_history_and_marks_interrupted_history() {
450 let items = responses::responses_input_for_provider(
451 &request(transcript()),
452 ProviderKind::Openai,
453 None,
454 );
455 assert_eq!(
456 roles(&items),
457 vec!["user", "assistant", "assistant", "system", "developer"],
458 "Responses preserves positioned system/developer history and drops unknown roles",
459 );
460 let rendered = serde_json::to_string(&items).expect("serialize");
461 assert!(rendered.contains("compaction summary"), "{rendered}");
462 assert!(rendered.contains("developer instruction"), "{rendered}");
463 assert!(!rendered.contains("from later"), "{rendered}");
464 assert_eq!(
465 items[2]["content"][0]["text"]
466 .as_str()
467 .expect("output text"),
468 format!("{INTERRUPTED_ASSISTANT_CONTEXT_PREFIX}half an answer"),
469 );
470 }
471
472 /// Anthropic accepts only user/assistant message roles. Positioned system
473 /// and developer history is projected onto user without moving or dropping
474 /// its content; genuinely unknown roles are still refused at the seam.
475 #[test]
476 fn anthropic_never_emits_a_role_outside_user_and_assistant() {
477 for role in [Role::System, Role::Developer] {
478 let value = anthropic::message_to_anthropic(&message(role.clone(), "body"))
479 .expect("positioned instruction history is carried");
480 assert_eq!(value["role"], json!("user"), "{role}");
481 }
482 for role in [
483 Role::Unrecognized("future_role".to_string()),
484 Role::Unrecognized("tool".to_string()),
485 ] {
486 assert!(
487 anthropic::message_to_anthropic(&message(role.clone(), "body")).is_none(),
488 "anthropic must not put {role} on the wire",
489 );
490 }
491 for (role, expected) in [(Role::User, "user"), (Role::Assistant, "assistant")] {
492 let value =
493 anthropic::message_to_anthropic(&message(role, "body")).expect("carried role");
494 assert_eq!(value["role"], json!(expected));
495 }
496 }
497
498 #[test]
499 fn anthropic_marks_interrupted_assistant_history() {
500 let value =
501 anthropic::message_to_anthropic(&message(Role::InterruptedAssistant, "half an answer"))
502 .expect("interrupted output replays as assistant");
503 assert_eq!(value["role"], json!("assistant"));
504 assert_eq!(
505 value["content"][0]["text"].as_str().expect("text block"),
506 format!("{INTERRUPTED_ASSISTANT_CONTEXT_PREFIX}half an answer"),
507 );
508 }
509
510 #[test]
511 fn latest_reminder_validates_position_and_content() {
512 use super::super::role_placement::{
513 RolePlacement, WireDialect, role_placement, validate_latest_reminder_messages,
514 };
515
516 let valid = vec![
517 message(Role::LatestReminder, "remember concise citations"),
518 message(Role::User, "summarize the results"),
519 ];
520 validate_latest_reminder_messages(&valid)
521 .expect("latest_reminder immediately before user is valid");
522
523 assert_eq!(
524 role_placement(&Role::LatestReminder, WireDialect::AnthropicMessages),
525 RolePlacement::LatestReminder
526 );
527 assert_eq!(
528 role_placement(&Role::LatestReminder, WireDialect::ChatCompletions),
529 RolePlacement::LatestReminder
530 );
531 assert!(matches!(
532 role_placement(&Role::LatestReminder, WireDialect::OpenAiResponses),
533 RolePlacement::Rejected
534 ));
535
536 let empty = vec![
537 message(Role::LatestReminder, " "),
538 message(Role::User, "hi"),
539 ];
540 assert!(validate_latest_reminder_messages(&empty).is_err());
541
542 let trailing = vec![
543 message(Role::User, "hi"),
544 message(Role::LatestReminder, "too late"),
545 ];
546 assert!(validate_latest_reminder_messages(&trailing).is_err());
547
548 let between_tools = vec![
549 Message {
550 role: Role::Assistant,
551 content: vec![ContentBlock::ToolUse {
552 id: "call_1".to_string(),
553 name: "read_file".to_string(),
554 input: json!({"path": "a.txt"}),
555 caller: None,
556 thought_signature: None,
557 execution_id: None,
558 }],
559 },
560 message(Role::LatestReminder, "do not inject here"),
561 Message {
562 role: Role::User,
563 content: vec![ContentBlock::ToolResult {
564 tool_use_id: "call_1".to_string(),
565 content: "ok".to_string(),
566 is_error: None,
567 content_blocks: None,
568 execution_id: None,
569 }],
570 },
571 ];
572 assert!(validate_latest_reminder_messages(&between_tools).is_err());
573 }
574 }
575
575 lines RUST