Skip to main content

abyss_plugin_protocol/
event.rs

1//! Language-neutral Agent event wire types shared by the broker and Rust SDK.
2//!
3//! These types are independent of the current backend ingest request. A
4//! delivery plugin may translate an event into its destination's API without
5//! making that remote API part of the broker contract.
6//! Agent event compatibility is part of the broker plugin protocol version, so
7//! an individual event does not carry a separate schema version.
8
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11mod conversation;
12pub use conversation::{ContentCompleteness, Conversation, ConversationMessage, MessageRole};
13
14/// One event decoded with the contract defined by the active plugin protocol.
15#[derive(Debug, Deserialize, Serialize)]
16#[serde(deny_unknown_fields)]
17pub struct AgentEvent {
18    /// Stable event identifier assigned by the event producer.
19    pub event_id: String,
20    /// Time at which the broker observed the logical event.
21    pub occurred_at: DateTime<Utc>,
22    /// Device context observed by the broker.
23    pub device: DeviceContext,
24    /// Agent product context inferred from traffic.
25    pub agent: AgentContext,
26    /// Provider or collector session identifier.
27    pub session_id: String,
28    /// The user turn this request works for, as the Agent declares it in its
29    /// request headers; unique within the session. Absent when the request
30    /// works for no particular turn.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub turn_id: Option<String>,
33    /// Whether the request comes from a thread the Agent opened only to name
34    /// another session.
35    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
36    pub naming_thread: bool,
37    /// The thread that sent this exchange's request, as the Agent declares it.
38    /// Requests with the same value continue one conversation. Absent when
39    /// the Agent declares none.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub stream_id: Option<String>,
42    /// Provider identity of the response this exchange produced. Both events
43    /// of the exchange carry it, and later requests continue after it by this
44    /// value.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub response_id: Option<String>,
47    /// The response this exchange's request continues after; the request then
48    /// carries only the messages added since that response.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub previous_response_id: Option<String>,
51    /// What the Agent made this provider call for, when its traffic says so.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub purpose: Option<EventPurpose>,
54    /// Title the Agent generated for the session this event belongs to;
55    /// response side of a [`EventPurpose::SessionTitle`] call only.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub session_title: Option<String>,
58    /// Provider and model context.
59    pub llm: LlmContext,
60    /// Request or response side represented by this event.
61    pub side: AgentEventSide,
62    /// Policy-retained request or response text.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub text: Option<String>,
65    /// Role-aware request or response messages.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub conversation: Option<Conversation>,
68    /// Token counters attributed to this event side.
69    pub token_usage: TokenUsage,
70    /// Normalized tool calls associated with this event side.
71    #[serde(default, skip_serializing_if = "Vec::is_empty")]
72    pub tool_calls: Vec<ToolCall>,
73    /// Normalized tool results associated with this event side.
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    pub tool_results: Vec<ToolResult>,
76    /// Policy-retained image attachments.
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub attachments: Vec<ImageAttachment>,
79}
80
81/// Agent-declared reason for a provider call.
82#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
83#[serde(rename_all = "snake_case")]
84#[non_exhaustive]
85pub enum EventPurpose {
86    /// The Agent explicitly disables generation while warming a provider connection.
87    /// Its observed usage is retained but is outside completed inference-turn usage.
88    Prewarm,
89    /// The Agent asks the model to name the session the call belongs to.
90    SessionTitle,
91    /// The Agent asks the model to summarize the conversation so far, to
92    /// continue from the summary instead of the full history.
93    Compaction,
94}
95
96/// Device context attached to one Agent event.
97#[derive(Debug, Deserialize, Serialize)]
98#[serde(deny_unknown_fields)]
99pub struct DeviceContext {
100    /// Human-readable host name.
101    pub host_name: String,
102    /// Platform namespace such as `linux`, `macos`, or `windows`.
103    pub platform: String,
104    /// Operating-system version when available.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub os_version: Option<String>,
107}
108
109/// Agent product context attached to one Agent event.
110#[derive(Debug, Deserialize, Serialize)]
111#[serde(deny_unknown_fields)]
112pub struct AgentContext {
113    /// Product name such as `codex` or `claude-code`.
114    pub name: String,
115    /// Agent version when it can be inferred from traffic.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub version: Option<String>,
118}
119
120/// LLM provider and model context attached to one Agent event.
121#[derive(Debug, Deserialize, Serialize)]
122#[serde(deny_unknown_fields)]
123pub struct LlmContext {
124    /// Provider namespace with typed variants for built-in providers.
125    pub provider: LlmProvider,
126    /// Provider model name.
127    pub model: String,
128}
129
130/// Known and extension LLM provider namespaces.
131#[derive(Debug, Eq, PartialEq)]
132#[non_exhaustive]
133pub enum LlmProvider {
134    /// OpenAI-compatible first-party API traffic.
135    OpenAi,
136    /// Anthropic first-party API traffic.
137    Anthropic,
138    /// Provider namespace not yet represented by a built-in variant.
139    Other(String),
140}
141
142impl LlmProvider {
143    /// Creates a provider from its wire namespace.
144    #[must_use]
145    pub fn from_wire_name(provider: String) -> Self {
146        match provider.as_str() {
147            "openai" => Self::OpenAi,
148            "anthropic" => Self::Anthropic,
149            _ => Self::Other(provider),
150        }
151    }
152
153    /// Returns the provider namespace carried on the wire.
154    #[must_use]
155    pub fn wire_name(&self) -> &str {
156        match self {
157            Self::OpenAi => "openai",
158            Self::Anthropic => "anthropic",
159            Self::Other(provider) => provider,
160        }
161    }
162}
163
164impl Serialize for LlmProvider {
165    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166    where
167        S: Serializer,
168    {
169        serializer.serialize_str(self.wire_name())
170    }
171}
172
173impl<'de> Deserialize<'de> for LlmProvider {
174    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
175    where
176        D: Deserializer<'de>,
177    {
178        String::deserialize(deserializer).map(Self::from_wire_name)
179    }
180}
181
182/// Request or response side represented by one usage event.
183#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
184#[non_exhaustive]
185#[serde(rename_all = "snake_case")]
186pub enum AgentEventSide {
187    /// Agent request content and input-side token usage.
188    Request,
189    /// Provider response content and output-side token usage.
190    Response,
191}
192
193impl AgentEventSide {
194    /// Returns the request/response name carried by backend translations.
195    #[must_use]
196    pub const fn wire_name(self) -> &'static str {
197        match self {
198            Self::Request => "request",
199            Self::Response => "response",
200        }
201    }
202}
203
204/// One normalized model-requested tool invocation.
205#[derive(Debug, Deserialize, Serialize)]
206#[serde(deny_unknown_fields)]
207pub struct ToolCall {
208    /// Broker-normalized identifier shared with the corresponding tool result.
209    pub call_id: String,
210    /// Broker-normalized tool name, such as `Bash`, `Read`, or `exec`.
211    pub name: String,
212    /// Complete provider-visible tool input normalized as text by the broker.
213    pub input: String,
214    /// Lowercase SHA-256 digest of `input`.
215    pub input_sha256: String,
216}
217
218/// One normalized result submitted back to the model after a tool call.
219#[derive(Debug, Deserialize, Serialize)]
220#[serde(deny_unknown_fields)]
221pub struct ToolResult {
222    /// Broker-normalized identifier shared with the originating tool call.
223    pub call_id: String,
224    /// Provider-visible result normalized as text by the broker.
225    pub output: String,
226    /// Lowercase SHA-256 digest of `output`.
227    pub output_sha256: String,
228}
229
230/// Normalized non-negative token counters.
231///
232/// Input, cache read, cache write, and output counters are disjoint;
233/// `reasoning_tokens` is a breakdown of `output_tokens`.
234#[derive(Debug, Deserialize, Serialize)]
235#[serde(deny_unknown_fields)]
236pub struct TokenUsage {
237    /// Input tokens neither read from nor written into a provider cache.
238    pub input_tokens: u64,
239    /// Tokens produced by model output, including reasoning.
240    pub output_tokens: u64,
241    /// Input tokens read from a provider cache.
242    pub cache_read_tokens: u64,
243    /// Input tokens written into a provider cache.
244    pub cache_write_tokens: u64,
245    /// Part of `output_tokens` spent in model reasoning traces.
246    pub reasoning_tokens: u64,
247    /// Sum of input, cache read, cache write, and output counters.
248    pub total_tokens: u64,
249}
250
251/// One policy-retained image attachment.
252#[derive(Debug, Deserialize, Serialize)]
253#[serde(deny_unknown_fields)]
254pub struct ImageAttachment {
255    /// Stable zero-based presentation position within the event.
256    pub position: u32,
257    /// Validated image media type.
258    pub media_type: ImageMediaType,
259    /// Decoded byte count before base64 transport encoding.
260    pub byte_size: u64,
261    /// Lowercase SHA-256 digest of the decoded image bytes.
262    pub sha256: String,
263    /// Image content when policy permits full image retention.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub content_base64: Option<String>,
266}
267
268/// Image media types supported by broker plugin protocol version 1.
269#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
270#[non_exhaustive]
271pub enum ImageMediaType {
272    /// Portable Network Graphics.
273    #[serde(rename = "image/png")]
274    Png,
275    /// Joint Photographic Experts Group image.
276    #[serde(rename = "image/jpeg")]
277    Jpeg,
278    /// WebP image.
279    #[serde(rename = "image/webp")]
280    Webp,
281    /// Graphics Interchange Format image.
282    #[serde(rename = "image/gif")]
283    Gif,
284}
285
286impl ImageMediaType {
287    /// Returns the MIME type carried on the wire.
288    #[must_use]
289    pub const fn wire_name(self) -> &'static str {
290        match self {
291            Self::Png => "image/png",
292            Self::Jpeg => "image/jpeg",
293            Self::Webp => "image/webp",
294            Self::Gif => "image/gif",
295        }
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::{
302        AgentContext, AgentEvent, AgentEventSide, DeviceContext, LlmContext, LlmProvider,
303        TokenUsage, ToolCall, ToolResult,
304    };
305    use chrono::{TimeZone as _, Utc};
306
307    #[test]
308    fn agent_event_serializes_as_one_flat_typed_payload() {
309        let event = sample_event(LlmProvider::OpenAi);
310        let serialized = serde_json::to_value(event).expect("Agent event should serialize");
311
312        assert!(
313            serialized.get("schema_version").is_none(),
314            "Agent events should be versioned by the plugin protocol"
315        );
316        assert_eq!(
317            serialized["side"], "request",
318            "the event side should be a direct typed field"
319        );
320        assert!(
321            serialized.get("event_type").is_none() && serialized.get("payload").is_none(),
322            "a single event kind should not add a speculative discriminator or payload wrapper"
323        );
324        assert!(
325            serialized.get("metadata").is_none(),
326            "the public event must not expose an unstructured metadata object"
327        );
328        assert!(
329            serialized.get("text").is_none(),
330            "absent optional content should be omitted"
331        );
332        for field in [
333            "turn_id",
334            "naming_thread",
335            "stream_id",
336            "response_id",
337            "previous_response_id",
338            "purpose",
339            "session_title",
340            "conversation",
341        ] {
342            assert!(
343                serialized.get(field).is_none(),
344                "absent {field} should be omitted"
345            );
346        }
347    }
348
349    #[test]
350    fn tool_activity_serializes_as_named_structures() {
351        let mut event = sample_event(LlmProvider::OpenAi);
352        event.tool_calls.push(ToolCall {
353            call_id: "call-1".to_owned(),
354            name: "exec".to_owned(),
355            input: "pwd".to_owned(),
356            input_sha256: "call-hash".to_owned(),
357        });
358        event.tool_results.push(ToolResult {
359            call_id: "call-1".to_owned(),
360            output: "/workspace".to_owned(),
361            output_sha256: "result-hash".to_owned(),
362        });
363
364        let serialized = serde_json::to_value(event).expect("Agent event should serialize");
365
366        assert_eq!(serialized["tool_calls"][0]["name"], "exec");
367        assert_eq!(serialized["tool_calls"][0]["input"], "pwd");
368        assert_eq!(serialized["tool_results"][0]["call_id"], "call-1");
369        assert_eq!(serialized["tool_results"][0]["output"], "/workspace");
370    }
371
372    #[test]
373    fn agent_event_rejects_an_unstructured_metadata_object() {
374        let mut serialized = serde_json::to_value(sample_event(LlmProvider::OpenAi))
375            .expect("event should serialize");
376        serialized["metadata"] = serde_json::json!({"provider_private_field": true});
377
378        let error = serde_json::from_value::<AgentEvent>(serialized)
379            .expect_err("undeclared metadata should be rejected");
380
381        assert!(
382            error.to_string().contains("unknown field `metadata`"),
383            "error should identify metadata as outside the public contract"
384        );
385    }
386
387    #[test]
388    fn extension_provider_namespace_round_trips() {
389        let serialized = serde_json::to_value(sample_event(LlmProvider::Other(
390            "customer-private-llm".to_owned(),
391        )))
392        .expect("Agent event should serialize");
393        let decoded: AgentEvent =
394            serde_json::from_value(serialized).expect("Agent event should deserialize");
395
396        assert_eq!(
397            decoded.llm.provider,
398            LlmProvider::Other("customer-private-llm".to_owned()),
399            "unknown provider namespaces should be preserved"
400        );
401    }
402
403    fn sample_event(provider: LlmProvider) -> AgentEvent {
404        AgentEvent {
405            event_id: "evt-test".to_owned(),
406            occurred_at: Utc
407                .with_ymd_and_hms(2026, 8, 19, 10, 0, 0)
408                .single()
409                .expect("sample timestamp should be valid"),
410            device: DeviceContext {
411                host_name: "test-host".to_owned(),
412                platform: "macos".to_owned(),
413                os_version: None,
414            },
415            agent: AgentContext {
416                name: "codex".to_owned(),
417                version: None,
418            },
419            session_id: "session-1".to_owned(),
420            turn_id: None,
421            naming_thread: false,
422            stream_id: None,
423            response_id: None,
424            previous_response_id: None,
425            purpose: None,
426            session_title: None,
427            llm: LlmContext {
428                provider,
429                model: "gpt-test".to_owned(),
430            },
431            side: AgentEventSide::Request,
432            text: None,
433            conversation: None,
434            token_usage: TokenUsage {
435                input_tokens: 10,
436                output_tokens: 0,
437                cache_read_tokens: 0,
438                cache_write_tokens: 0,
439                reasoning_tokens: 0,
440                total_tokens: 10,
441            },
442            tool_calls: Vec::new(),
443            tool_results: Vec::new(),
444            attachments: Vec::new(),
445        }
446    }
447}