use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
mod conversation;
pub use conversation::{ContentCompleteness, Conversation, ConversationEntry, EntryRole};
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AgentEvent {
pub event_id: String,
pub observed_at: DateTime<Utc>,
pub device: DeviceContext,
pub agent: AgentContext,
pub session_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub previous_response_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subagent_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_subagent_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub turn_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purpose: Option<EventPurpose>,
pub llm: LlmContext,
pub side: AgentEventSide,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub omitted: Vec<ContentCategory>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation: Option<Conversation>,
pub path: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub headers: Vec<HttpHeader>,
pub token_usage: TokenUsage,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<ImageAttachment>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ContentCategory {
TokenUsage,
ConversationText,
ToolContent,
Images,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(try_from = "HttpHeaderWire", into = "HttpHeaderWire")]
pub struct HttpHeader {
pub name: String,
pub value: HttpHeaderValue,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum HttpHeaderValue {
Text(String),
Base64(String),
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct HttpHeaderWire {
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
value_base64: Option<String>,
}
impl TryFrom<HttpHeaderWire> for HttpHeader {
type Error = &'static str;
fn try_from(wire: HttpHeaderWire) -> Result<Self, Self::Error> {
let value = match (wire.value, wire.value_base64) {
(Some(value), None) => HttpHeaderValue::Text(value),
(None, Some(value)) => HttpHeaderValue::Base64(value),
_ => return Err("a header carries exactly one of `value` and `value_base64`"),
};
Ok(Self {
name: wire.name,
value,
})
}
}
impl From<HttpHeader> for HttpHeaderWire {
fn from(header: HttpHeader) -> Self {
let (value, value_base64) = match header.value {
HttpHeaderValue::Text(value) => (Some(value), None),
HttpHeaderValue::Base64(value) => (None, Some(value)),
};
Self {
name: header.name,
value,
value_base64,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventPurpose {
Prewarm,
SessionTitle,
Compaction,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceContext {
pub host_name: String,
pub platform: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub os_version: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AgentContext {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LlmContext {
pub provider: LlmProvider,
pub model: String,
}
#[derive(Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LlmProvider {
OpenAi,
Anthropic,
Other(String),
}
impl LlmProvider {
#[must_use]
pub fn from_wire_name(provider: String) -> Self {
match provider.as_str() {
"openai" => Self::OpenAi,
"anthropic" => Self::Anthropic,
_ => Self::Other(provider),
}
}
#[must_use]
pub fn wire_name(&self) -> &str {
match self {
Self::OpenAi => "openai",
Self::Anthropic => "anthropic",
Self::Other(provider) => provider,
}
}
}
impl Serialize for LlmProvider {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.wire_name())
}
}
impl<'de> Deserialize<'de> for LlmProvider {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).map(Self::from_wire_name)
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum AgentEventSide {
Request,
Response,
}
impl AgentEventSide {
#[must_use]
pub const fn wire_name(self) -> &'static str {
match self {
Self::Request => "request",
Self::Response => "response",
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TokenUsage {
pub input_tokens: u64,
pub output_tokens: u64,
pub cache_read_tokens: u64,
pub cache_write_tokens: u64,
pub reasoning_tokens: u64,
pub total_tokens: u64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ImageAttachment {
pub position: u32,
pub media_type: ImageMediaType,
pub byte_size: u64,
pub sha256: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_base64: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[non_exhaustive]
pub enum ImageMediaType {
#[serde(rename = "image/png")]
Png,
#[serde(rename = "image/jpeg")]
Jpeg,
#[serde(rename = "image/webp")]
Webp,
#[serde(rename = "image/gif")]
Gif,
}
impl ImageMediaType {
#[must_use]
pub const fn wire_name(self) -> &'static str {
match self {
Self::Png => "image/png",
Self::Jpeg => "image/jpeg",
Self::Webp => "image/webp",
Self::Gif => "image/gif",
}
}
}
#[cfg(test)]
mod tests {
use super::{
AgentContext, AgentEvent, AgentEventSide, ContentCategory, DeviceContext, HttpHeader,
HttpHeaderValue, LlmContext, LlmProvider, TokenUsage,
};
use chrono::{TimeZone as _, Utc};
#[test]
fn agent_event_serializes_as_one_flat_typed_payload() {
let event = sample_event(LlmProvider::OpenAi);
let serialized = serde_json::to_value(event).expect("Agent event should serialize");
assert!(
serialized.get("schema_version").is_none(),
"Agent events should be versioned by the plugin protocol"
);
assert_eq!(
serialized["side"], "request",
"the event side should be a direct typed field"
);
assert!(
serialized.get("event_type").is_none() && serialized.get("payload").is_none(),
"a single event kind should not add a speculative discriminator or payload wrapper"
);
assert!(
serialized.get("metadata").is_none(),
"the public event must not expose an unstructured metadata object"
);
for field in [
"response_id",
"previous_response_id",
"subagent_id",
"parent_subagent_id",
"turn_id",
"purpose",
"omitted",
"conversation",
"headers",
] {
assert!(
serialized.get(field).is_none(),
"absent {field} should be omitted"
);
}
}
#[test]
fn declared_ids_serialize_verbatim_when_present() {
let mut event = sample_event(LlmProvider::Anthropic);
event.subagent_id = Some("agent-2".to_owned());
event.parent_subagent_id = Some("agent-1".to_owned());
event.turn_id = Some(" turn {1} ".to_owned());
let serialized = serde_json::to_value(event).expect("Agent event should serialize");
assert_eq!(serialized["subagent_id"], "agent-2");
assert_eq!(serialized["parent_subagent_id"], "agent-1");
assert_eq!(serialized["turn_id"], " turn {1} ");
let decoded: AgentEvent =
serde_json::from_value(serialized).expect("declared ids should round-trip");
assert_eq!(decoded.turn_id.as_deref(), Some(" turn {1} "));
}
#[test]
fn request_headers_carry_exactly_one_value_form() {
let mut event = sample_event(LlmProvider::OpenAi);
event.headers = vec![
HttpHeader {
name: "session-id".to_owned(),
value: HttpHeaderValue::Text("s-1".to_owned()),
},
HttpHeader {
name: "x-binary".to_owned(),
value: HttpHeaderValue::Base64("//4=".to_owned()),
},
];
let serialized = serde_json::to_value(event).expect("Agent event should serialize");
assert_eq!(
serialized["headers"],
serde_json::json!([
{"name": "session-id", "value": "s-1"},
{"name": "x-binary", "value_base64": "//4="}
])
);
let decoded: AgentEvent =
serde_json::from_value(serialized.clone()).expect("headers should round-trip");
assert_eq!(decoded.headers.len(), 2);
for invalid in [
serde_json::json!({"name": "a"}),
serde_json::json!({"name": "a", "value": "v", "value_base64": "dg=="}),
serde_json::json!({"name": "a", "value": "v", "raw": true}),
] {
let mut event = serialized.clone();
event["headers"] = serde_json::json!([invalid]);
assert!(serde_json::from_value::<AgentEvent>(event).is_err());
}
}
#[test]
fn omitted_categories_use_snake_case_names() {
let mut event = sample_event(LlmProvider::OpenAi);
event.omitted = vec![
ContentCategory::TokenUsage,
ContentCategory::ConversationText,
ContentCategory::ToolContent,
ContentCategory::Images,
];
let serialized = serde_json::to_value(event).expect("Agent event should serialize");
assert_eq!(
serialized["omitted"],
serde_json::json!(["token_usage", "conversation_text", "tool_content", "images"])
);
}
#[test]
fn agent_event_rejects_an_unstructured_metadata_object() {
let mut serialized = serde_json::to_value(sample_event(LlmProvider::OpenAi))
.expect("event should serialize");
serialized["metadata"] = serde_json::json!({"provider_private_field": true});
let error = serde_json::from_value::<AgentEvent>(serialized)
.expect_err("undeclared metadata should be rejected");
assert!(
error.to_string().contains("unknown field `metadata`"),
"error should identify metadata as outside the public contract"
);
}
#[test]
fn content_outside_conversation_entries_is_rejected() {
let serialized = serde_json::to_value(sample_event(LlmProvider::OpenAi))
.expect("event should serialize");
for (field, value) in [
("text", serde_json::json!("hello")),
("tool_calls", serde_json::json!([])),
("tool_results", serde_json::json!([])),
] {
let mut event = serialized.clone();
event[field] = value;
assert!(
serde_json::from_value::<AgentEvent>(event).is_err(),
"{field} is carried only by conversation entries"
);
}
}
#[test]
fn extension_provider_namespace_round_trips() {
let serialized = serde_json::to_value(sample_event(LlmProvider::Other(
"customer-private-llm".to_owned(),
)))
.expect("Agent event should serialize");
let decoded: AgentEvent =
serde_json::from_value(serialized).expect("Agent event should deserialize");
assert_eq!(
decoded.llm.provider,
LlmProvider::Other("customer-private-llm".to_owned()),
"unknown provider namespaces should be preserved"
);
}
fn sample_event(provider: LlmProvider) -> AgentEvent {
AgentEvent {
event_id: "evt-test".to_owned(),
observed_at: Utc
.with_ymd_and_hms(2026, 8, 19, 10, 0, 0)
.single()
.expect("sample timestamp should be valid"),
device: DeviceContext {
host_name: "test-host".to_owned(),
platform: "macos".to_owned(),
os_version: None,
},
agent: AgentContext {
name: "codex".to_owned(),
version: None,
},
session_id: "session-1".to_owned(),
response_id: None,
previous_response_id: None,
subagent_id: None,
parent_subagent_id: None,
turn_id: None,
purpose: None,
llm: LlmContext {
provider,
model: "gpt-test".to_owned(),
},
side: AgentEventSide::Request,
omitted: Vec::new(),
conversation: None,
path: "/v1/responses".to_owned(),
headers: Vec::new(),
token_usage: TokenUsage {
input_tokens: 10,
output_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
reasoning_tokens: 0,
total_tokens: 10,
},
attachments: Vec::new(),
}
}
}