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    /// One entry per protocol block or item, in provider order, never merged
10    /// or split.
11    pub entries: Vec<ConversationEntry>,
12    /// Whether the captured body could be completely decoded.
13    pub completeness: ContentCompleteness,
14}
15
16/// One protocol block or item.
17#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
18#[serde(deny_unknown_fields)]
19pub struct ConversationEntry {
20    /// What the block is, by the protocol block-to-role table.
21    pub role: EntryRole,
22    /// Visible text; a tool call's arguments or input as sent, a tool result's
23    /// output.
24    pub text: String,
25    /// Identifier pairing a tool call with its result; tool entries only.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub call_id: Option<String>,
28    /// Tool name; tool calls only.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub name: Option<String>,
31    /// Identity of the item the entry belongs to, as the traffic carries it.
32    /// A model output keeps the identity its provider assigned when a later
33    /// request sends it back as history, so the request entry and the
34    /// response entry that produced it carry the same value.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub item_id: Option<String>,
37}
38
39/// Role of one conversation entry.
40#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
41#[serde(rename_all = "snake_case")]
42#[non_exhaustive]
43pub enum EntryRole {
44    /// System prompt block.
45    System,
46    /// Developer message part.
47    Developer,
48    /// End-user text.
49    User,
50    /// Model-visible assistant text.
51    Assistant,
52    /// Model reasoning, such as thinking blocks or reasoning summaries.
53    Reasoning,
54    /// A tool call; `text` is its arguments or input.
55    ToolCall,
56    /// A tool result; `text` is its output.
57    ToolResult,
58    /// Any other block or item that carries text.
59    Unknown,
60}
61
62/// Decoding state independent of successful provider execution.
63#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
64#[serde(rename_all = "snake_case")]
65#[non_exhaustive]
66pub enum ContentCompleteness {
67    /// Captured documents were decoded completely.
68    Complete,
69    /// Capture or document decoding is incomplete.
70    Partial,
71    /// No supported structured document could be decoded.
72    Unsupported,
73}
74
75#[cfg(test)]
76mod tests {
77    use super::{ContentCompleteness, Conversation, ConversationEntry, EntryRole};
78    use serde_json::json;
79
80    #[test]
81    fn roles_use_the_published_snake_case_names() {
82        let roles = [
83            (EntryRole::System, "system"),
84            (EntryRole::Developer, "developer"),
85            (EntryRole::User, "user"),
86            (EntryRole::Assistant, "assistant"),
87            (EntryRole::Reasoning, "reasoning"),
88            (EntryRole::ToolCall, "tool_call"),
89            (EntryRole::ToolResult, "tool_result"),
90            (EntryRole::Unknown, "unknown"),
91        ];
92        for (role, wire) in roles {
93            assert_eq!(serde_json::to_value(role).unwrap(), wire);
94            assert_eq!(
95                serde_json::from_value::<EntryRole>(json!(wire)).unwrap(),
96                role
97            );
98        }
99        assert!(serde_json::from_value::<EntryRole>(json!("tool")).is_err());
100    }
101
102    #[test]
103    fn identities_are_omitted_when_absent() {
104        let conversation = Conversation {
105            entries: vec![
106                ConversationEntry {
107                    role: EntryRole::User,
108                    text: "run pwd".to_owned(),
109                    call_id: None,
110                    name: None,
111                    item_id: None,
112                },
113                ConversationEntry {
114                    role: EntryRole::ToolCall,
115                    text: "{\"cmd\":\"pwd\"}".to_owned(),
116                    call_id: Some("call_1".to_owned()),
117                    name: Some("exec".to_owned()),
118                    item_id: Some("fc_1".to_owned()),
119                },
120            ],
121            completeness: ContentCompleteness::Complete,
122        };
123
124        assert_eq!(
125            serde_json::to_value(&conversation).unwrap(),
126            json!({
127                "entries": [
128                    {"role": "user", "text": "run pwd"},
129                    {"role": "tool_call", "text": "{\"cmd\":\"pwd\"}", "call_id": "call_1", "name": "exec", "item_id": "fc_1"}
130                ],
131                "completeness": "complete"
132            })
133        );
134    }
135
136    #[test]
137    fn undeclared_and_raw_fields_are_rejected() {
138        let conversation = json!({
139            "entries": [{"role": "user", "text": "hello"}],
140            "completeness": "partial"
141        });
142        serde_json::from_value::<Conversation>(conversation.clone())
143            .expect("the structured conversation should decode");
144
145        for (path, value) in [
146            ("messages", json!([])),
147            ("instructions_present", json!(true)),
148            ("policy_omitted", json!(false)),
149            ("payloads", json!([{"output": []}])),
150        ] {
151            let mut undeclared = conversation.clone();
152            undeclared[path] = value;
153            assert!(
154                serde_json::from_value::<Conversation>(undeclared).is_err(),
155                "{path}"
156            );
157        }
158        let mut with_id = conversation;
159        with_id["entries"][0]["id"] = json!("m1");
160        assert!(serde_json::from_value::<Conversation>(with_id).is_err());
161    }
162}