返回 CodeWhale
role.rs
根目录 / crates / protocol / src / role.rs
1 //! The closed set of message roles Codewhale can put on a transcript.
2 //!
3 //! Roles used to be free-form `String`s on [`crate::request::Message`], and
4 //! four wire adapters each decided independently what an unfamiliar role
5 //! meant: two dropped it silently, one forwarded it verbatim for the provider
6 //! to reject, one failed closed. [`Role`] closes the set so that decision can
7 //! be made once, in one table, instead of four times by accident.
8 //!
9 //! Two properties are load-bearing and are covered by tests:
10 //!
11 //! * **Byte-identical serialization.** A `Role` serializes as exactly the
12 //! string it replaced and deserializes from any string. Saved transcripts
13 //! therefore need no schema bump and no migration ladder, and a session
14 //! written by a newer build still loads here — an unfamiliar role lands in
15 //! [`Role::Unrecognized`] rather than failing the whole session load.
16 //! * **`assistant_interrupted` stays distinct.** The interrupted-assistant
17 //! sentinel is its own variant, not a flavour of [`Role::Assistant`], so it
18 //! keeps round-tripping as a separate session item.
19
20 use std::fmt;
21
22 use serde::{Deserialize, Deserializer, Serialize, Serializer};
23
24 use crate::request::INTERRUPTED_ASSISTANT_ROLE;
25
26 /// Who authored a message in a transcript.
27 ///
28 /// `Unrecognized` is deliberately part of the type: it is what lets a
29 /// transcript written by a future build round-trip through this one. It
30 /// carries no trust and grants no placement of its own — see the wire
31 /// adapters' placement table for what each dialect does with it.
32 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
33 pub enum Role {
34 /// Input authored by the human operator or by the harness on their behalf.
35 User,
36 /// Output authored by the model.
37 Assistant,
38 /// Harness-authored context injected into the transcript body — compaction
39 /// summaries, branch summaries, sub-agent framing.
40 System,
41 /// Provider-supported instruction content embedded at a transcript
42 /// position. Unlike the top-level system prompt, this role is load-bearing
43 /// history and must retain its position on wires that support it.
44 Developer,
45 /// Assistant text that was visible before the turn was interrupted. Kept
46 /// distinct from [`Role::Assistant`] so replay can mark it as incomplete.
47 InterruptedAssistant,
48 LatestReminder,
49 /// A role string this build does not know. Preserved verbatim so loading
50 /// and re-saving a transcript is lossless.
51 Unrecognized(String),
52 }
53
54 impl Role {
55 /// The exact wire/persisted string for this role.
56 ///
57 /// This is the serialization; do not let it drift from [`Serialize`].
58 #[must_use]
59 pub fn as_str(&self) -> &str {
60 match self {
61 Self::User => "user",
62 Self::Assistant => "assistant",
63 Self::System => "system",
64 Self::Developer => "developer",
65 Self::InterruptedAssistant => INTERRUPTED_ASSISTANT_ROLE,
66 Self::LatestReminder => "latest_reminder",
67 Self::Unrecognized(raw) => raw.as_str(),
68 }
69 }
70
71 /// True for roles the model itself authored, interrupted output included.
72 #[must_use]
73 pub fn is_assistant_like(&self) -> bool {
74 matches!(self, Self::Assistant | Self::InterruptedAssistant)
75 }
76 }
77
78 impl From<&str> for Role {
79 fn from(value: &str) -> Self {
80 match value {
81 "user" => Self::User,
82 "assistant" => Self::Assistant,
83 "system" => Self::System,
84 "developer" => Self::Developer,
85 INTERRUPTED_ASSISTANT_ROLE => Self::InterruptedAssistant,
86 "latest_reminder" => Self::LatestReminder,
87 other => Self::Unrecognized(other.to_string()),
88 }
89 }
90 }
91
92 impl From<String> for Role {
93 fn from(value: String) -> Self {
94 match value.as_str() {
95 "user" => Self::User,
96 "assistant" => Self::Assistant,
97 "system" => Self::System,
98 "developer" => Self::Developer,
99 INTERRUPTED_ASSISTANT_ROLE => Self::InterruptedAssistant,
100 "latest_reminder" => Self::LatestReminder,
101 _ => Self::Unrecognized(value),
102 }
103 }
104 }
105
106 impl fmt::Display for Role {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 f.write_str(self.as_str())
109 }
110 }
111
112 impl PartialEq<str> for Role {
113 fn eq(&self, other: &str) -> bool {
114 self.as_str() == other
115 }
116 }
117
118 impl PartialEq<&str> for Role {
119 fn eq(&self, other: &&str) -> bool {
120 self.as_str() == *other
121 }
122 }
123
124 impl PartialEq<String> for Role {
125 fn eq(&self, other: &String) -> bool {
126 self.as_str() == other.as_str()
127 }
128 }
129
130 impl PartialEq<Role> for str {
131 fn eq(&self, other: &Role) -> bool {
132 self == other.as_str()
133 }
134 }
135
136 impl PartialEq<Role> for &str {
137 fn eq(&self, other: &Role) -> bool {
138 *self == other.as_str()
139 }
140 }
141
142 impl PartialEq<Role> for String {
143 fn eq(&self, other: &Role) -> bool {
144 self.as_str() == other.as_str()
145 }
146 }
147
148 impl Serialize for Role {
149 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
150 serializer.serialize_str(self.as_str())
151 }
152 }
153
154 impl<'de> Deserialize<'de> for Role {
155 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
156 Ok(Self::from(String::deserialize(deserializer)?))
157 }
158 }
159
160 #[cfg(test)]
161 mod tests {
162 use super::Role;
163 use crate::request::INTERRUPTED_ASSISTANT_ROLE;
164
165 #[test]
166 fn known_roles_serialize_as_the_strings_they_replaced() {
167 for (role, expected) in [
168 (Role::User, "\"user\""),
169 (Role::Assistant, "\"assistant\""),
170 (Role::System, "\"system\""),
171 (Role::Developer, "\"developer\""),
172 (Role::InterruptedAssistant, "\"assistant_interrupted\""),
173 ] {
174 assert_eq!(serde_json::to_string(&role).expect("serialize"), expected);
175 }
176 }
177
178 #[test]
179 fn serialized_bytes_match_the_raw_string_encoding() {
180 // The persisted format must not shift: a `Role` has to produce the
181 // same bytes the `String` field produced, or every saved session
182 // would need a schema bump and a migration ladder.
183 for raw in [
184 "user",
185 "assistant",
186 "system",
187 "developer",
188 INTERRUPTED_ASSISTANT_ROLE,
189 ] {
190 assert_eq!(
191 serde_json::to_vec(&Role::from(raw)).expect("serialize role"),
192 serde_json::to_vec(raw).expect("serialize string"),
193 "role {raw} must serialize like its string",
194 );
195 }
196 }
197
198 #[test]
199 fn unknown_roles_round_trip_verbatim() {
200 let role = Role::from("future_role");
201 assert_eq!(role, Role::Unrecognized("future_role".to_string()));
202 let encoded = serde_json::to_string(&role).expect("serialize");
203 assert_eq!(encoded, "\"future_role\"");
204 let decoded: Role = serde_json::from_str(&encoded).expect("deserialize");
205 assert_eq!(decoded, role);
206 }
207
208 #[test]
209 fn interrupted_assistant_is_not_assistant() {
210 let decoded: Role =
211 serde_json::from_str("\"assistant_interrupted\"").expect("deserialize sentinel");
212 assert_eq!(decoded, Role::InterruptedAssistant);
213 assert_ne!(decoded, Role::Assistant);
214 assert_ne!(decoded, "assistant");
215 assert!(decoded.is_assistant_like());
216 }
217
218 #[test]
219 fn string_comparisons_work_in_both_directions() {
220 assert_eq!(Role::User, "user");
221 assert_eq!("user", Role::User);
222 assert_eq!(Role::User, "user".to_string());
223 assert_ne!(Role::System, "user");
224 }
225
226 #[test]
227 fn latest_reminder_round_trips_distinct_from_system_and_user() {
228 assert_eq!(Role::from("latest_reminder"), Role::LatestReminder);
229 assert_eq!(Role::LatestReminder.as_str(), "latest_reminder");
230 let encoded = serde_json::to_string(&Role::LatestReminder).expect("serialize");
231 assert_eq!(encoded, "\"latest_reminder\"");
232 let decoded: Role = serde_json::from_str(&encoded).expect("deserialize");
233 assert_eq!(decoded, Role::LatestReminder);
234 assert_ne!(decoded, Role::User);
235 assert_ne!(decoded, Role::System);
236 }
237 }
238
238 lines RUST