use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde_json::Value; use thiserror::Error; use crate::{ActiveSlotKind, PROTOCOL_VERSION, ServerCapabilities, ToolProposal}; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase")] pub struct EventMetadata { pub protocol_version: String, pub event_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub request_id: Option, /// Untrusted server hint. Local routing must use `BoundGatewayEvent.profile_id`. #[serde(rename = "profileId", default, skip_serializing_if = "Option::is_none")] pub server_profile_hint: Option, pub server_instance_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub conversation_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub message_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub session_id: Option, pub timestamp: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub sequence: Option, } impl EventMetadata { pub fn new( event_id: impl Into, server_instance_id: impl Into, timestamp: impl Into, sequence: u64, ) -> Self { Self { protocol_version: PROTOCOL_VERSION.to_owned(), event_id: event_id.into(), request_id: None, server_profile_hint: None, server_instance_id: server_instance_id.into(), conversation_id: None, message_id: None, session_id: None, timestamp: timestamp.into(), sequence: Some(sequence), } } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct HeartbeatPayload { pub interval_ms: u64, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MessageDeltaPayload { pub delta: String, pub index: u32, } #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase")] pub enum FinishReason { Stop, Cancelled, Error, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MessageCompletedPayload { pub finish_reason: FinishReason, #[serde(default, skip_serializing_if = "Option::is_none")] pub content: Option, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProactiveMessagePayload { pub content: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub notification_title: Option, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AgentStatusPayload { pub state: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub detail: Option, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct GatewayErrorPayload { pub code: String, pub message: String, pub retryable: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(tag = "eventType", content = "payload")] pub enum GatewayEventBody { #[serde(rename = "system.heartbeat")] Heartbeat(HeartbeatPayload), #[serde(rename = "message.delta")] MessageDelta(MessageDeltaPayload), #[serde(rename = "message.completed")] MessageCompleted(MessageCompletedPayload), #[serde(rename = "message.proactive")] ProactiveMessage(ProactiveMessagePayload), #[serde(rename = "agent.status")] AgentStatus(AgentStatusPayload), #[serde(rename = "tool.proposal")] ToolProposal(ToolProposal), #[serde(rename = "capabilities.changed")] CapabilitiesChanged(ServerCapabilities), #[serde(rename = "error")] Error(GatewayErrorPayload), } impl GatewayEventBody { pub fn event_type(&self) -> &'static str { match self { Self::Heartbeat(_) => "system.heartbeat", Self::MessageDelta(_) => "message.delta", Self::MessageCompleted(_) => "message.completed", Self::ProactiveMessage(_) => "message.proactive", Self::AgentStatus(_) => "agent.status", Self::ToolProposal(_) => "tool.proposal", Self::CapabilitiesChanged(_) => "capabilities.changed", Self::Error(_) => "error", } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct GatewayEvent { #[serde(flatten)] pub metadata: EventMetadata, #[serde(flatten)] pub body: GatewayEventBody, } impl GatewayEvent { pub fn new(metadata: EventMetadata, body: GatewayEventBody) -> Self { Self { metadata, body } } pub fn event_type(&self) -> &'static str { self.body.event_type() } } /// Two-stage wire representation used before a payload type is trusted. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProtocolEnvelope { pub protocol_version: String, pub event_type: String, pub event_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub request_id: Option, /// This value is never used as the local profile binding. #[serde(rename = "profileId", default, skip_serializing_if = "Option::is_none")] pub server_profile_hint: Option, pub server_instance_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub conversation_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub message_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub session_id: Option, pub timestamp: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub sequence: Option, pub payload: Value, } /// Alias used by connection code to emphasize that the envelope remains /// untrusted until it is decoded and locally bound. pub type RawProtocolEnvelope = ProtocolEnvelope; impl TryFrom for GatewayEvent { type Error = ProtocolError; fn try_from(raw: RawProtocolEnvelope) -> Result { if raw.protocol_version != PROTOCOL_VERSION { return Err(ProtocolError::IncompatibleProtocolVersion { received: raw.protocol_version, }); } require_non_empty("eventId", &raw.event_id)?; require_non_empty("serverInstanceId", &raw.server_instance_id)?; require_non_empty("timestamp", &raw.timestamp)?; let event_type = raw.event_type; let body = match event_type.as_str() { "system.heartbeat" => GatewayEventBody::Heartbeat(decode(&event_type, raw.payload)?), "message.delta" => GatewayEventBody::MessageDelta(decode(&event_type, raw.payload)?), "message.completed" => { GatewayEventBody::MessageCompleted(decode(&event_type, raw.payload)?) } "message.proactive" => { GatewayEventBody::ProactiveMessage(decode(&event_type, raw.payload)?) } "agent.status" => GatewayEventBody::AgentStatus(decode(&event_type, raw.payload)?), "tool.proposal" => GatewayEventBody::ToolProposal(decode(&event_type, raw.payload)?), "capabilities.changed" => { GatewayEventBody::CapabilitiesChanged(decode(&event_type, raw.payload)?) } "error" => GatewayEventBody::Error(decode(&event_type, raw.payload)?), _ => return Err(ProtocolError::UnsupportedEventType { event_type }), }; Ok(Self { metadata: EventMetadata { protocol_version: PROTOCOL_VERSION.to_owned(), event_id: raw.event_id, request_id: raw.request_id, server_profile_hint: raw.server_profile_hint, server_instance_id: raw.server_instance_id, conversation_id: raw.conversation_id, message_id: raw.message_id, session_id: raw.session_id, timestamp: raw.timestamp, sequence: raw.sequence, }, body, }) } } fn decode(event_type: &str, payload: Value) -> Result { serde_json::from_value(payload).map_err(|source| ProtocolError::InvalidPayload { event_type: event_type.to_owned(), source, }) } fn require_non_empty(field: &'static str, value: &str) -> Result<(), ProtocolError> { if value.trim().is_empty() { Err(ProtocolError::EmptyRequiredField { field }) } else { Ok(()) } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct BoundGatewayEvent { /// Trusted local profile binding supplied by the connection object. pub profile_id: String, pub slot: ActiveSlotKind, pub event: GatewayEvent, } impl BoundGatewayEvent { pub fn bind( raw: RawProtocolEnvelope, local_profile_id: impl Into, slot: ActiveSlotKind, expected_server_instance_id: &str, ) -> Result { let local_profile_id = local_profile_id.into(); require_non_empty("localProfileId", &local_profile_id)?; let event = GatewayEvent::try_from(raw)?; if event.metadata.server_instance_id != expected_server_instance_id { return Err(ProtocolError::ServerInstanceMismatch { expected: expected_server_instance_id.to_owned(), received: event.metadata.server_instance_id, }); } Ok(Self { profile_id: local_profile_id, slot, event, }) } } #[derive(Debug, Error)] pub enum ProtocolError { #[error("unsupported protocol version: {received}")] IncompatibleProtocolVersion { received: String }, #[error("required field {field} is empty")] EmptyRequiredField { field: &'static str }, #[error("unsupported gateway event type: {event_type}")] UnsupportedEventType { event_type: String }, #[error("invalid payload for {event_type}: {source}")] InvalidPayload { event_type: String, #[source] source: serde_json::Error, }, #[error("server instance mismatch: expected {expected}, received {received}")] ServerInstanceMismatch { expected: String, received: String }, }