1use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct as _};
4use serde_json::Value;
5
6use crate::event::{Conversation, EventPurpose, ImageAttachment, LlmProvider};
7
8#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
10#[serde(rename_all = "snake_case")]
11#[non_exhaustive]
12pub enum PluginCapability {
13 AgentEvents,
15 AgentRequest,
17}
18
19#[derive(Debug, Deserialize, Serialize)]
21#[serde(tag = "encoding", content = "content", rename_all = "snake_case")]
22#[non_exhaustive]
23pub enum DecodedContent {
24 Utf8(String),
26 Base64(String),
28}
29
30#[derive(Debug, Deserialize, Serialize)]
32#[serde(rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum RequestParsingStatus {
35 Parsed,
37 UnknownProtocol,
39 InvalidPayload,
41}
42
43#[derive(Debug, Deserialize, Serialize)]
45#[serde(rename_all = "snake_case")]
46#[non_exhaustive]
47pub enum RequestMessageType {
48 Text,
49 Binary,
50}
51
52#[derive(Debug, Deserialize, Serialize)]
54#[serde(deny_unknown_fields)]
55pub struct RequestSourceProcess {
56 pub pid: Option<u32>,
58 pub pid_version: Option<u32>,
60 pub name: Option<String>,
62 pub executable_path: Option<String>,
64 pub application_id: Option<String>,
66 pub entry_point: Option<String>,
68 pub working_directory: Option<String>,
70}
71
72#[derive(Debug, Deserialize, Serialize)]
74#[serde(deny_unknown_fields)]
75pub struct RequestHarness {
76 pub id: String,
78 pub version: Option<String>,
80 pub turn_id: Option<String>,
82 pub subagent_id: Option<String>,
84 pub parent_subagent_id: Option<String>,
86 pub purpose: Option<EventPurpose>,
88}
89
90#[derive(Debug, Deserialize, Serialize)]
92#[serde(deny_unknown_fields)]
93pub struct AgentRequestProjection {
94 pub protocol: String,
96 pub provider: LlmProvider,
98 pub model: Option<String>,
100 pub conversation: Conversation,
102 pub attachments: Vec<ImageAttachment>,
104 pub tools: Option<Value>,
106 pub previous_response_id: Option<String>,
108}
109
110#[derive(Deserialize, Serialize)]
112#[serde(deny_unknown_fields)]
113pub struct AgentRequestContext {
114 pub flow_id: String,
116 pub request_id: String,
118 pub ingress: String,
120 pub source_process: Option<RequestSourceProcess>,
122 pub destination: String,
124 pub destination_host: Option<String>,
126 pub server_name: Option<String>,
128 pub authority: Option<String>,
130 pub proxy_endpoint: Option<String>,
132 pub method: String,
134 pub path: String,
136 pub websocket: bool,
138 pub sequence: u64,
140 pub message_type: Option<RequestMessageType>,
142 pub headers: Vec<(String, String)>,
145 pub body: DecodedContent,
147 pub json: Option<Value>,
149 pub parsing_status: RequestParsingStatus,
151 pub harness: Option<RequestHarness>,
153 pub auth_token: Option<String>,
155 pub auth_token_writable: bool,
157 pub model_writable: bool,
159 pub agent: Option<AgentRequestProjection>,
161}
162
163impl std::fmt::Debug for AgentRequestContext {
164 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 formatter
166 .debug_struct("AgentRequestContext")
167 .field("request_id", &self.request_id)
168 .field("parsing_status", &self.parsing_status)
169 .finish_non_exhaustive()
170 }
171}
172
173#[derive(Debug, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct InspectResponse {
177 pub request_id: String,
179 pub decision: RequestDecision,
181}
182
183#[derive(Serialize, PartialEq, Eq)]
185#[serde(
186 tag = "op",
187 content = "value",
188 rename_all = "snake_case",
189 deny_unknown_fields
190)]
191#[non_exhaustive]
192pub enum ModifyAction {
193 SetAuthToken(String),
195 RemoveAuthToken,
197 SetModel(String),
199 RemoveModel,
201}
202
203impl<'de> Deserialize<'de> for ModifyAction {
204 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
205 #[derive(Deserialize)]
206 #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
207 #[expect(
208 clippy::empty_enum_variants_with_brackets,
209 reason = "serde unit variants ignore extra fields; empty struct variants enforce the wire schema"
210 )]
211 enum WireAction {
212 SetAuthToken { value: String },
213 RemoveAuthToken {},
214 SetModel { value: String },
215 RemoveModel {},
216 }
217 Ok(match WireAction::deserialize(deserializer)? {
218 WireAction::SetAuthToken { value } => Self::SetAuthToken(value),
219 WireAction::RemoveAuthToken {} => Self::RemoveAuthToken,
220 WireAction::SetModel { value } => Self::SetModel(value),
221 WireAction::RemoveModel {} => Self::RemoveModel,
222 })
223 }
224}
225
226impl std::fmt::Debug for ModifyAction {
227 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 formatter.write_str(match self {
229 Self::SetAuthToken(_) => "SetAuthToken(<redacted>)",
230 Self::RemoveAuthToken => "RemoveAuthToken",
231 Self::SetModel(_) => "SetModel(<redacted>)",
232 Self::RemoveModel => "RemoveModel",
233 })
234 }
235}
236
237#[derive(Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum RequestDecision {
241 Allow,
243 Block(String),
245 Modify(Box<[ModifyAction]>),
247}
248
249impl RequestDecision {
250 #[must_use]
252 pub const fn into_response(self, request_id: String) -> InspectResponse {
253 InspectResponse {
254 request_id,
255 decision: self,
256 }
257 }
258}
259
260impl Serialize for RequestDecision {
261 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
262 let fields = if matches!(self, Self::Allow) { 1 } else { 2 };
263 let mut object = serializer.serialize_struct("RequestDecision", fields)?;
264 match self {
265 Self::Allow => object.serialize_field("action", "allow")?,
266 Self::Block(reason) => {
267 object.serialize_field("action", "block")?;
268 object.serialize_field("reason", reason)?;
269 }
270 Self::Modify(actions) => {
271 object.serialize_field("action", "modify")?;
272 object.serialize_field("actions", actions)?;
273 }
274 }
275 object.end()
276 }
277}
278
279impl<'de> Deserialize<'de> for RequestDecision {
280 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
281 #[derive(Deserialize)]
282 #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
283 #[expect(
284 clippy::empty_enum_variants_with_brackets,
285 reason = "serde unit variants ignore extra fields; empty struct variants enforce the wire schema"
286 )]
287 enum WireDecision {
288 Allow {},
289 Block { reason: String },
290 Modify { actions: Box<[ModifyAction]> },
291 }
292 Ok(match WireDecision::deserialize(deserializer)? {
293 WireDecision::Allow {} => Self::Allow,
294 WireDecision::Block { reason } => Self::Block(reason),
295 WireDecision::Modify { actions } => Self::Modify(actions),
296 })
297 }
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303 use serde_json::json;
304
305 #[test]
306 fn decisions_round_trip_explicit_actions_without_context() {
307 for value in [
308 json!({"action":"allow"}),
309 json!({"action":"block","reason":"policy"}),
310 json!({"action":"modify","actions":[]}),
311 json!({"action":"modify","actions":[{"op":"set_auth_token","value":"private-token"},{"op":"remove_auth_token"},{"op":"set_model","value":"new"},{"op":"remove_model"}]}),
312 ] {
313 let decision: RequestDecision = serde_json::from_value(value.clone()).unwrap();
314 assert!(!format!("{decision:?}").contains("private-token"));
315 assert_eq!(serde_json::to_value(decision).unwrap(), value);
316 }
317 for invalid in [
318 json!({"action":"allow","actions":[]}),
319 json!({"action":"block"}),
320 json!({"action":"modify","actions":[{"op":"set_auth_token"}]}),
321 json!({"action":"modify","actions":[{"op":"set_auth_token","value":null}]}),
322 json!({"action":"modify","actions":[{"op":"remove_model","value":"bad"}]}),
323 json!({"action":"modify","actions":[{"op":"remove_model","value":null}]}),
324 json!({"action":"modify","actions":[{"op":"replace_body","value":"bad"}]}),
325 ] {
326 assert!(
327 serde_json::from_value::<RequestDecision>(invalid.clone()).is_err(),
328 "unexpectedly accepted {invalid}"
329 );
330 }
331 }
332}