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, ConversationEntry, EntryRole};
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 observed_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    /// Provider identity of the response this exchange produced. Both events
29    /// of the exchange carry it, and later requests continue after it by this
30    /// value.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub response_id: Option<String>,
33    /// The response this exchange's request continues after; the request then
34    /// carries only the messages added since that response.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub previous_response_id: Option<String>,
37    /// Id of the subagent this exchange belongs to, as the client declared it;
38    /// absent for the main agent and for side requests.
39    ///
40    /// Each declared id is read only from the request headers (for a WebSocket
41    /// connection, its upgrade request's), taken verbatim, and absent when no
42    /// header declares it; no value is substituted. Both events of an exchange
43    /// carry it.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub subagent_id: Option<String>,
46    /// Id of the subagent that spawned this exchange's subagent, declared like
47    /// `subagent_id`; absent when the main agent spawned it.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub parent_subagent_id: Option<String>,
50    /// Root turn the client declares, like `subagent_id`: the user input this
51    /// exchange ultimately works for. A subagent's exchanges carry the value
52    /// of the turn that spawned it; an exchange the client makes for no turn
53    /// carries none.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub turn_id: Option<String>,
56    /// What the Agent made this provider call for, when its traffic says so.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub purpose: Option<EventPurpose>,
59    /// Provider and model context.
60    pub llm: LlmContext,
61    /// Request or response side represented by this event.
62    pub side: AgentEventSide,
63    /// Content categories the effective content policy omitted from this
64    /// event; empty when everything was retained.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub omitted: Vec<ContentCategory>,
67    /// Role-aware request or response entries, one per protocol block or
68    /// item; the only carrier of the side's content.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub conversation: Option<Conversation>,
71    /// The exchange's request target: its path and query as the request named
72    /// them (for a WebSocket connection, its upgrade request's), verbatim.
73    /// Both events of an exchange carry it.
74    pub path: String,
75    /// Captured headers of this event's side: request headers on a request
76    /// event, response headers on a response event. In capture order,
77    /// duplicates kept, verbatim except that credential values are redacted.
78    #[serde(default, skip_serializing_if = "Vec::is_empty")]
79    pub headers: Vec<HttpHeader>,
80    /// Token counters attributed to this event side.
81    pub token_usage: TokenUsage,
82    /// Policy-retained image attachments.
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub attachments: Vec<ImageAttachment>,
85}
86
87/// A category of captured content the content policy can omit.
88#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
89#[serde(rename_all = "snake_case")]
90#[non_exhaustive]
91pub enum ContentCategory {
92    /// Token counters; when omitted every counter is zero.
93    TokenUsage,
94    /// Text of non-tool conversation entries; when omitted those entries keep
95    /// their role and `item_id` with empty text.
96    ConversationText,
97    /// Tool arguments and results; when omitted tool entries keep their
98    /// `call_id`, `name`, and `item_id` with empty text.
99    ToolContent,
100    /// Image attachments; when omitted no attachment is carried.
101    Images,
102}
103
104/// One captured request or response header.
105#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
106#[serde(try_from = "HttpHeaderWire", into = "HttpHeaderWire")]
107pub struct HttpHeader {
108    /// Header name as captured.
109    pub name: String,
110    /// Header value as captured.
111    pub value: HttpHeaderValue,
112}
113
114/// Captured header value bytes.
115#[derive(Clone, Debug, Eq, PartialEq)]
116#[non_exhaustive]
117pub enum HttpHeaderValue {
118    /// The value bytes are valid UTF-8; carried as `value`.
119    Text(String),
120    /// The value bytes are not valid UTF-8; carried base64-encoded as
121    /// `value_base64`.
122    Base64(String),
123}
124
125/// Wire shape of [`HttpHeader`]: exactly one of `value` and `value_base64`.
126#[derive(Deserialize, Serialize)]
127#[serde(deny_unknown_fields)]
128struct HttpHeaderWire {
129    name: String,
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    value: Option<String>,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    value_base64: Option<String>,
134}
135
136impl TryFrom<HttpHeaderWire> for HttpHeader {
137    type Error = &'static str;
138
139    fn try_from(wire: HttpHeaderWire) -> Result<Self, Self::Error> {
140        let value = match (wire.value, wire.value_base64) {
141            (Some(value), None) => HttpHeaderValue::Text(value),
142            (None, Some(value)) => HttpHeaderValue::Base64(value),
143            _ => return Err("a header carries exactly one of `value` and `value_base64`"),
144        };
145        Ok(Self {
146            name: wire.name,
147            value,
148        })
149    }
150}
151
152impl From<HttpHeader> for HttpHeaderWire {
153    fn from(header: HttpHeader) -> Self {
154        let (value, value_base64) = match header.value {
155            HttpHeaderValue::Text(value) => (Some(value), None),
156            HttpHeaderValue::Base64(value) => (None, Some(value)),
157        };
158        Self {
159            name: header.name,
160            value,
161            value_base64,
162        }
163    }
164}
165
166/// Agent-declared reason for a provider call.
167#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
168#[serde(rename_all = "snake_case")]
169#[non_exhaustive]
170pub enum EventPurpose {
171    /// The Agent explicitly disables generation while warming a provider connection.
172    /// Its observed usage is retained but is outside completed inference-turn usage.
173    Prewarm,
174    /// The Agent asks the model to name the session the call belongs to.
175    SessionTitle,
176    /// The Agent asks the model to summarize the conversation so far, to
177    /// continue from the summary instead of the full history.
178    Compaction,
179}
180
181/// Device context attached to one Agent event.
182#[derive(Debug, Deserialize, Serialize)]
183#[serde(deny_unknown_fields)]
184pub struct DeviceContext {
185    /// Human-readable host name.
186    pub host_name: String,
187    /// Platform namespace such as `linux`, `macos`, or `windows`.
188    pub platform: String,
189    /// Operating-system version when available.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub os_version: Option<String>,
192}
193
194/// Agent product context attached to one Agent event.
195#[derive(Debug, Deserialize, Serialize)]
196#[serde(deny_unknown_fields)]
197pub struct AgentContext {
198    /// Product name such as `codex` or `claude-code`.
199    pub name: String,
200    /// Agent version when it can be inferred from traffic.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub version: Option<String>,
203}
204
205/// LLM provider and model context attached to one Agent event.
206#[derive(Debug, Deserialize, Serialize)]
207#[serde(deny_unknown_fields)]
208pub struct LlmContext {
209    /// Provider namespace with typed variants for built-in providers.
210    pub provider: LlmProvider,
211    /// Provider model name.
212    pub model: String,
213}
214
215/// Known and extension LLM provider namespaces.
216#[derive(Debug, Eq, PartialEq)]
217#[non_exhaustive]
218pub enum LlmProvider {
219    /// OpenAI-compatible first-party API traffic.
220    OpenAi,
221    /// Anthropic first-party API traffic.
222    Anthropic,
223    /// Provider namespace not yet represented by a built-in variant.
224    Other(String),
225}
226
227impl LlmProvider {
228    /// Creates a provider from its wire namespace.
229    #[must_use]
230    pub fn from_wire_name(provider: String) -> Self {
231        match provider.as_str() {
232            "openai" => Self::OpenAi,
233            "anthropic" => Self::Anthropic,
234            _ => Self::Other(provider),
235        }
236    }
237
238    /// Returns the provider namespace carried on the wire.
239    #[must_use]
240    pub fn wire_name(&self) -> &str {
241        match self {
242            Self::OpenAi => "openai",
243            Self::Anthropic => "anthropic",
244            Self::Other(provider) => provider,
245        }
246    }
247}
248
249impl Serialize for LlmProvider {
250    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
251    where
252        S: Serializer,
253    {
254        serializer.serialize_str(self.wire_name())
255    }
256}
257
258impl<'de> Deserialize<'de> for LlmProvider {
259    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
260    where
261        D: Deserializer<'de>,
262    {
263        String::deserialize(deserializer).map(Self::from_wire_name)
264    }
265}
266
267/// Request or response side represented by one usage event.
268#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
269#[non_exhaustive]
270#[serde(rename_all = "snake_case")]
271pub enum AgentEventSide {
272    /// Agent request content and input-side token usage.
273    Request,
274    /// Provider response content and output-side token usage.
275    Response,
276}
277
278impl AgentEventSide {
279    /// Returns the wire name of this side: `request` or `response`.
280    #[must_use]
281    pub const fn wire_name(self) -> &'static str {
282        match self {
283            Self::Request => "request",
284            Self::Response => "response",
285        }
286    }
287}
288
289/// Normalized non-negative token counters.
290///
291/// Input, cache read, cache write, and output counters are disjoint;
292/// `reasoning_tokens` is a breakdown of `output_tokens`.
293#[derive(Debug, Deserialize, Serialize)]
294#[serde(deny_unknown_fields)]
295pub struct TokenUsage {
296    /// Input tokens neither read from nor written into a provider cache.
297    pub input_tokens: u64,
298    /// Tokens produced by model output, including reasoning.
299    pub output_tokens: u64,
300    /// Input tokens read from a provider cache.
301    pub cache_read_tokens: u64,
302    /// Input tokens written into a provider cache.
303    pub cache_write_tokens: u64,
304    /// Part of `output_tokens` spent in model reasoning traces.
305    pub reasoning_tokens: u64,
306    /// Sum of input, cache read, cache write, and output counters.
307    pub total_tokens: u64,
308}
309
310/// One policy-retained image attachment.
311#[derive(Debug, Deserialize, Serialize)]
312#[serde(deny_unknown_fields)]
313pub struct ImageAttachment {
314    /// Stable zero-based presentation position within the event.
315    pub position: u32,
316    /// Validated image media type.
317    pub media_type: ImageMediaType,
318    /// Decoded byte count before base64 transport encoding.
319    pub byte_size: u64,
320    /// Lowercase SHA-256 digest of the decoded image bytes.
321    pub sha256: String,
322    /// Image content when policy permits full image retention.
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub content_base64: Option<String>,
325}
326
327/// Image media types supported by broker plugin protocol version 1.
328#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
329#[non_exhaustive]
330pub enum ImageMediaType {
331    /// Portable Network Graphics.
332    #[serde(rename = "image/png")]
333    Png,
334    /// Joint Photographic Experts Group image.
335    #[serde(rename = "image/jpeg")]
336    Jpeg,
337    /// WebP image.
338    #[serde(rename = "image/webp")]
339    Webp,
340    /// Graphics Interchange Format image.
341    #[serde(rename = "image/gif")]
342    Gif,
343}
344
345impl ImageMediaType {
346    /// Returns the MIME type carried on the wire.
347    #[must_use]
348    pub const fn wire_name(self) -> &'static str {
349        match self {
350            Self::Png => "image/png",
351            Self::Jpeg => "image/jpeg",
352            Self::Webp => "image/webp",
353            Self::Gif => "image/gif",
354        }
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::{
361        AgentContext, AgentEvent, AgentEventSide, ContentCategory, DeviceContext, HttpHeader,
362        HttpHeaderValue, LlmContext, LlmProvider, TokenUsage,
363    };
364    use chrono::{TimeZone as _, Utc};
365
366    #[test]
367    fn agent_event_serializes_as_one_flat_typed_payload() {
368        let event = sample_event(LlmProvider::OpenAi);
369        let serialized = serde_json::to_value(event).expect("Agent event should serialize");
370
371        assert!(
372            serialized.get("schema_version").is_none(),
373            "Agent events should be versioned by the plugin protocol"
374        );
375        assert_eq!(
376            serialized["side"], "request",
377            "the event side should be a direct typed field"
378        );
379        assert!(
380            serialized.get("event_type").is_none() && serialized.get("payload").is_none(),
381            "a single event kind should not add a speculative discriminator or payload wrapper"
382        );
383        assert!(
384            serialized.get("metadata").is_none(),
385            "the public event must not expose an unstructured metadata object"
386        );
387        for field in [
388            "response_id",
389            "previous_response_id",
390            "subagent_id",
391            "parent_subagent_id",
392            "turn_id",
393            "purpose",
394            "omitted",
395            "conversation",
396            "headers",
397        ] {
398            assert!(
399                serialized.get(field).is_none(),
400                "absent {field} should be omitted"
401            );
402        }
403    }
404
405    #[test]
406    fn declared_ids_serialize_verbatim_when_present() {
407        let mut event = sample_event(LlmProvider::Anthropic);
408        event.subagent_id = Some("agent-2".to_owned());
409        event.parent_subagent_id = Some("agent-1".to_owned());
410        event.turn_id = Some(" turn {1} ".to_owned());
411        let serialized = serde_json::to_value(event).expect("Agent event should serialize");
412
413        assert_eq!(serialized["subagent_id"], "agent-2");
414        assert_eq!(serialized["parent_subagent_id"], "agent-1");
415        assert_eq!(serialized["turn_id"], " turn {1} ");
416        let decoded: AgentEvent =
417            serde_json::from_value(serialized).expect("declared ids should round-trip");
418        assert_eq!(decoded.turn_id.as_deref(), Some(" turn {1} "));
419    }
420
421    #[test]
422    fn request_headers_carry_exactly_one_value_form() {
423        let mut event = sample_event(LlmProvider::OpenAi);
424        event.headers = vec![
425            HttpHeader {
426                name: "session-id".to_owned(),
427                value: HttpHeaderValue::Text("s-1".to_owned()),
428            },
429            HttpHeader {
430                name: "x-binary".to_owned(),
431                value: HttpHeaderValue::Base64("//4=".to_owned()),
432            },
433        ];
434        let serialized = serde_json::to_value(event).expect("Agent event should serialize");
435
436        assert_eq!(
437            serialized["headers"],
438            serde_json::json!([
439                {"name": "session-id", "value": "s-1"},
440                {"name": "x-binary", "value_base64": "//4="}
441            ])
442        );
443        let decoded: AgentEvent =
444            serde_json::from_value(serialized.clone()).expect("headers should round-trip");
445        assert_eq!(decoded.headers.len(), 2);
446        for invalid in [
447            serde_json::json!({"name": "a"}),
448            serde_json::json!({"name": "a", "value": "v", "value_base64": "dg=="}),
449            serde_json::json!({"name": "a", "value": "v", "raw": true}),
450        ] {
451            let mut event = serialized.clone();
452            event["headers"] = serde_json::json!([invalid]);
453            assert!(serde_json::from_value::<AgentEvent>(event).is_err());
454        }
455    }
456
457    #[test]
458    fn omitted_categories_use_snake_case_names() {
459        let mut event = sample_event(LlmProvider::OpenAi);
460        event.omitted = vec![
461            ContentCategory::TokenUsage,
462            ContentCategory::ConversationText,
463            ContentCategory::ToolContent,
464            ContentCategory::Images,
465        ];
466        let serialized = serde_json::to_value(event).expect("Agent event should serialize");
467
468        assert_eq!(
469            serialized["omitted"],
470            serde_json::json!(["token_usage", "conversation_text", "tool_content", "images"])
471        );
472    }
473
474    #[test]
475    fn agent_event_rejects_an_unstructured_metadata_object() {
476        let mut serialized = serde_json::to_value(sample_event(LlmProvider::OpenAi))
477            .expect("event should serialize");
478        serialized["metadata"] = serde_json::json!({"provider_private_field": true});
479
480        let error = serde_json::from_value::<AgentEvent>(serialized)
481            .expect_err("undeclared metadata should be rejected");
482
483        assert!(
484            error.to_string().contains("unknown field `metadata`"),
485            "error should identify metadata as outside the public contract"
486        );
487    }
488
489    #[test]
490    fn content_outside_conversation_entries_is_rejected() {
491        let serialized = serde_json::to_value(sample_event(LlmProvider::OpenAi))
492            .expect("event should serialize");
493        for (field, value) in [
494            ("text", serde_json::json!("hello")),
495            ("tool_calls", serde_json::json!([])),
496            ("tool_results", serde_json::json!([])),
497        ] {
498            let mut event = serialized.clone();
499            event[field] = value;
500            assert!(
501                serde_json::from_value::<AgentEvent>(event).is_err(),
502                "{field} is carried only by conversation entries"
503            );
504        }
505    }
506
507    #[test]
508    fn extension_provider_namespace_round_trips() {
509        let serialized = serde_json::to_value(sample_event(LlmProvider::Other(
510            "customer-private-llm".to_owned(),
511        )))
512        .expect("Agent event should serialize");
513        let decoded: AgentEvent =
514            serde_json::from_value(serialized).expect("Agent event should deserialize");
515
516        assert_eq!(
517            decoded.llm.provider,
518            LlmProvider::Other("customer-private-llm".to_owned()),
519            "unknown provider namespaces should be preserved"
520        );
521    }
522
523    fn sample_event(provider: LlmProvider) -> AgentEvent {
524        AgentEvent {
525            event_id: "evt-test".to_owned(),
526            observed_at: Utc
527                .with_ymd_and_hms(2026, 8, 19, 10, 0, 0)
528                .single()
529                .expect("sample timestamp should be valid"),
530            device: DeviceContext {
531                host_name: "test-host".to_owned(),
532                platform: "macos".to_owned(),
533                os_version: None,
534            },
535            agent: AgentContext {
536                name: "codex".to_owned(),
537                version: None,
538            },
539            session_id: "session-1".to_owned(),
540            response_id: None,
541            previous_response_id: None,
542            subagent_id: None,
543            parent_subagent_id: None,
544            turn_id: None,
545            purpose: None,
546            llm: LlmContext {
547                provider,
548                model: "gpt-test".to_owned(),
549            },
550            side: AgentEventSide::Request,
551            omitted: Vec::new(),
552            conversation: None,
553            path: "/v1/responses".to_owned(),
554            headers: Vec::new(),
555            token_usage: TokenUsage {
556                input_tokens: 10,
557                output_tokens: 0,
558                cache_read_tokens: 0,
559                cache_write_tokens: 0,
560                reasoning_tokens: 0,
561                total_tokens: 10,
562            },
563            attachments: Vec::new(),
564        }
565    }
566}