Skip to main content

abyss_plugin_protocol/event/
conversation.rs

1//! Structured provider content; consumers never need to decode transport bodies.
2
3use serde::{Deserialize, Serialize};
4
5/// Content observed on one side of a provider exchange.
6#[derive(Debug, Clone, Deserialize, Serialize)]
7#[serde(deny_unknown_fields)]
8pub struct Conversation {
9    /// Ordered messages, with streamed fragments assembled by the collector.
10    pub messages: Vec<ConversationMessage>,
11    /// Whether the request carried explicit instructions or a system prompt,
12    /// including an explicitly empty one.
13    pub instructions_present: bool,
14    /// Whether the captured input could be completely decoded.
15    pub completeness: ContentCompleteness,
16    /// Whether content policy omitted messages from this projection.
17    pub policy_omitted: bool,
18}
19
20/// A provider message or standalone item, preserving its role and order.
21#[derive(Debug, Clone, Deserialize, Serialize)]
22#[serde(deny_unknown_fields)]
23pub struct ConversationMessage {
24    /// Provider item/message identity, when supplied.
25    pub id: Option<String>,
26    /// Message role; reasoning and tool items use their own role.
27    pub role: MessageRole,
28    /// Text projection excluding tool arguments and results.
29    pub text: String,
30}
31
32/// Role of one conversation message.
33/// TODO Context.
34#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
35#[serde(rename_all = "snake_case")]
36#[non_exhaustive]
37pub enum MessageRole {
38    /// Provider system prompt.
39    System,
40    /// Developer instructions, including OpenAI `instructions`.
41    Developer,
42    /// End-user input.
43    User,
44    /// Model-visible assistant output.
45    Assistant,
46    /// Model reasoning, such as thinking blocks or reasoning summaries.
47    Reasoning,
48    /// Tool call or tool result item; its content is carried by tool fields.
49    Tool,
50    /// The provider did not declare a role.
51    Unknown,
52}
53
54/// Decoding state independent of successful provider execution.
55#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
56#[serde(rename_all = "snake_case")]
57#[non_exhaustive]
58pub enum ContentCompleteness {
59    /// Captured documents were decoded completely.
60    Complete,
61    /// Capture or document decoding is incomplete.
62    Partial,
63    /// No supported structured document could be decoded.
64    Unsupported,
65}
66
67#[cfg(test)]
68mod tests {
69    use super::{ContentCompleteness, Conversation, ConversationMessage, MessageRole};
70    use serde_json::json;
71
72    #[test]
73    fn roles_use_the_published_snake_case_names() {
74        let roles = [
75            (MessageRole::System, "system"),
76            (MessageRole::Developer, "developer"),
77            (MessageRole::User, "user"),
78            (MessageRole::Assistant, "assistant"),
79            (MessageRole::Reasoning, "reasoning"),
80            (MessageRole::Tool, "tool"),
81            (MessageRole::Unknown, "unknown"),
82        ];
83        for (role, wire) in roles {
84            assert_eq!(serde_json::to_value(role).unwrap(), wire);
85            assert_eq!(
86                serde_json::from_value::<MessageRole>(json!(wire)).unwrap(),
87                role
88            );
89        }
90        assert!(
91            serde_json::from_value::<MessageRole>(json!("request")).is_err(),
92            "the former placeholder role is replaced by `unknown`"
93        );
94    }
95
96    #[test]
97    fn anthropic_thinking_is_a_reasoning_message_sharing_the_message_id() {
98        let conversation = Conversation {
99            messages: vec![
100                ConversationMessage {
101                    id: Some("msg_1".to_owned()),
102                    role: MessageRole::Reasoning,
103                    text: "plan".to_owned(),
104                },
105                ConversationMessage {
106                    id: Some("msg_1".to_owned()),
107                    role: MessageRole::Assistant,
108                    text: "hi".to_owned(),
109                },
110            ],
111            instructions_present: false,
112            completeness: ContentCompleteness::Complete,
113            policy_omitted: false,
114        };
115
116        assert_eq!(
117            serde_json::to_value(&conversation).unwrap(),
118            json!({
119                "messages": [
120                    {"id": "msg_1", "role": "reasoning", "text": "plan"},
121                    {"id": "msg_1", "role": "assistant", "text": "hi"}
122                ],
123                "instructions_present": false,
124                "completeness": "complete",
125                "policy_omitted": false
126            })
127        );
128    }
129
130    #[test]
131    fn raw_content_carriers_are_rejected() {
132        let conversation = json!({
133            "messages": [{"id": null, "role": "user", "text": "hello"}],
134            "instructions_present": true,
135            "completeness": "partial",
136            "policy_omitted": false
137        });
138        serde_json::from_value::<Conversation>(conversation.clone())
139            .expect("the structured conversation should decode");
140
141        let mut with_payloads = conversation.clone();
142        with_payloads["payloads"] = json!([{"output": []}]);
143        assert!(serde_json::from_value::<Conversation>(with_payloads).is_err());
144
145        let mut with_blocks = conversation;
146        with_blocks["messages"][0]["blocks"] = json!([{"type": "text", "text": "hello"}]);
147        assert!(serde_json::from_value::<Conversation>(with_blocks).is_err());
148    }
149}