1use chrono::{DateTime, Utc};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11mod conversation;
12pub use conversation::{ContentCompleteness, Conversation, ConversationEntry, EntryRole};
13
14#[derive(Debug, Deserialize, Serialize)]
16#[serde(deny_unknown_fields)]
17pub struct AgentEvent {
18 pub event_id: String,
20 pub observed_at: DateTime<Utc>,
22 pub device: DeviceContext,
24 pub agent: AgentContext,
26 pub session_id: String,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub response_id: Option<String>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub previous_response_id: Option<String>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub subagent_id: Option<String>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub parent_subagent_id: Option<String>,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub turn_id: Option<String>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub purpose: Option<EventPurpose>,
59 pub llm: LlmContext,
61 pub side: AgentEventSide,
63 #[serde(default, skip_serializing_if = "Vec::is_empty")]
66 pub omitted: Vec<ContentCategory>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub conversation: Option<Conversation>,
71 pub path: String,
75 #[serde(default, skip_serializing_if = "Vec::is_empty")]
79 pub headers: Vec<HttpHeader>,
80 pub token_usage: TokenUsage,
82 #[serde(default, skip_serializing_if = "Vec::is_empty")]
84 pub attachments: Vec<ImageAttachment>,
85}
86
87#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
89#[serde(rename_all = "snake_case")]
90#[non_exhaustive]
91pub enum ContentCategory {
92 TokenUsage,
94 ConversationText,
97 ToolContent,
100 Images,
102}
103
104#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
106#[serde(try_from = "HttpHeaderWire", into = "HttpHeaderWire")]
107pub struct HttpHeader {
108 pub name: String,
110 pub value: HttpHeaderValue,
112}
113
114#[derive(Clone, Debug, Eq, PartialEq)]
116#[non_exhaustive]
117pub enum HttpHeaderValue {
118 Text(String),
120 Base64(String),
123}
124
125#[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
168#[serde(rename_all = "snake_case")]
169#[non_exhaustive]
170pub enum EventPurpose {
171 Prewarm,
174 SessionTitle,
176 Compaction,
179}
180
181#[derive(Debug, Deserialize, Serialize)]
183#[serde(deny_unknown_fields)]
184pub struct DeviceContext {
185 pub host_name: String,
187 pub platform: String,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub os_version: Option<String>,
192}
193
194#[derive(Debug, Deserialize, Serialize)]
196#[serde(deny_unknown_fields)]
197pub struct AgentContext {
198 pub name: String,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub version: Option<String>,
203}
204
205#[derive(Debug, Deserialize, Serialize)]
207#[serde(deny_unknown_fields)]
208pub struct LlmContext {
209 pub provider: LlmProvider,
211 pub model: String,
213}
214
215#[derive(Debug, Eq, PartialEq)]
217#[non_exhaustive]
218pub enum LlmProvider {
219 OpenAi,
221 Anthropic,
223 Other(String),
225}
226
227impl LlmProvider {
228 #[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 #[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
269#[non_exhaustive]
270#[serde(rename_all = "snake_case")]
271pub enum AgentEventSide {
272 Request,
274 Response,
276}
277
278impl AgentEventSide {
279 #[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#[derive(Debug, Deserialize, Serialize)]
294#[serde(deny_unknown_fields)]
295pub struct TokenUsage {
296 pub input_tokens: u64,
298 pub output_tokens: u64,
300 pub cache_read_tokens: u64,
302 pub cache_write_tokens: u64,
304 pub reasoning_tokens: u64,
306 pub total_tokens: u64,
308}
309
310#[derive(Debug, Deserialize, Serialize)]
312#[serde(deny_unknown_fields)]
313pub struct ImageAttachment {
314 pub position: u32,
316 pub media_type: ImageMediaType,
318 pub byte_size: u64,
320 pub sha256: String,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
324 pub content_base64: Option<String>,
325}
326
327#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
329#[non_exhaustive]
330pub enum ImageMediaType {
331 #[serde(rename = "image/png")]
333 Png,
334 #[serde(rename = "image/jpeg")]
336 Jpeg,
337 #[serde(rename = "image/webp")]
339 Webp,
340 #[serde(rename = "image/gif")]
342 Gif,
343}
344
345impl ImageMediaType {
346 #[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}