Skip to main content

abyss_plugin_protocol/
inspection.rs

1//! Request-only Agent inspection values exchanged on a broker plugin session.
2
3use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct as _};
4use serde_json::Value;
5
6use crate::event::{Conversation, EventPurpose, ImageAttachment, LlmProvider};
7
8/// Capabilities selected by a plugin for this connection.
9#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
10#[serde(rename_all = "snake_case")]
11#[non_exhaustive]
12pub enum PluginCapability {
13    /// Receive the existing observation event stream.
14    AgentEvents,
15    /// Decide on complete plaintext requests before forwarding.
16    AgentRequest,
17}
18
19/// Complete decoded bytes, without a lossy UTF-8 conversion.
20#[derive(Debug, Deserialize, Serialize)]
21#[serde(tag = "encoding", content = "content", rename_all = "snake_case")]
22#[non_exhaustive]
23pub enum DecodedContent {
24    /// UTF-8 text, including JSON and unknown text protocols.
25    Utf8(String),
26    /// Base64 of a binary payload.
27    Base64(String),
28}
29
30/// Result of projecting a decoded request onto known Agent protocols.
31#[derive(Debug, Deserialize, Serialize)]
32#[serde(rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum RequestParsingStatus {
35    /// Recognized protocol with a decoded JSON request.
36    Parsed,
37    /// No known protocol matched; complete content remains available.
38    UnknownProtocol,
39    /// A known protocol did not contain a valid JSON request.
40    InvalidPayload,
41}
42
43/// Reassembled WebSocket payload type, independent of content encoding.
44#[derive(Debug, Deserialize, Serialize)]
45#[serde(rename_all = "snake_case")]
46#[non_exhaustive]
47pub enum RequestMessageType {
48    Text,
49    Binary,
50}
51
52/// Source metadata supplied by the ingress; explicit proxy clients have none.
53#[derive(Debug, Deserialize, Serialize)]
54#[serde(deny_unknown_fields)]
55pub struct RequestSourceProcess {
56    /// OS process identifier.
57    pub pid: Option<u32>,
58    /// OS process incarnation identifier.
59    pub pid_version: Option<u32>,
60    /// Process name.
61    pub name: Option<String>,
62    /// Executable path.
63    pub executable_path: Option<String>,
64    /// Platform application identity.
65    pub application_id: Option<String>,
66    /// Runtime entry script path.
67    pub entry_point: Option<String>,
68    /// Working directory.
69    pub working_directory: Option<String>,
70}
71
72/// Request-side Harness recognition and declarations, independent of audit policy.
73#[derive(Debug, Deserialize, Serialize)]
74#[serde(deny_unknown_fields)]
75pub struct RequestHarness {
76    /// Recognized Harness name.
77    pub id: String,
78    /// Recognized version.
79    pub version: Option<String>,
80    /// Root user turn declared by the client, including for subagent requests.
81    pub turn_id: Option<String>,
82    /// Subagent identity explicitly declared by this client.
83    pub subagent_id: Option<String>,
84    /// Subagent that spawned this one, if declared.
85    pub parent_subagent_id: Option<String>,
86    /// Declared request purpose.
87    pub purpose: Option<EventPurpose>,
88}
89
90/// Request-only model projection. Response IDs, output and usage are not invented.
91#[derive(Debug, Deserialize, Serialize)]
92#[serde(deny_unknown_fields)]
93pub struct AgentRequestProjection {
94    /// Known wire dialect.
95    pub protocol: String,
96    /// Provider resolved from request routing.
97    pub provider: LlmProvider,
98    /// Model requested by the caller.
99    pub model: Option<String>,
100    /// Ordered protocol entries, including instructions, tool calls and results.
101    pub conversation: Conversation,
102    /// Embedded image content; referenced attachments remain in the original JSON.
103    pub attachments: Vec<ImageAttachment>,
104    /// Provider tool definitions, retaining provider-specific schemas.
105    pub tools: Option<Value>,
106    /// Response that this request continues, if declared.
107    pub previous_response_id: Option<String>,
108}
109
110/// Complete decision context for one HTTP request or client WebSocket data message.
111#[derive(Deserialize, Serialize)]
112#[serde(deny_unknown_fields)]
113pub struct AgentRequestContext {
114    /// Stable physical flow identity.
115    pub flow_id: String,
116    /// Unique request/message correlation identity.
117    pub request_id: String,
118    /// Transport ingress source label.
119    pub ingress: String,
120    /// Platform process identity, when available.
121    pub source_process: Option<RequestSourceProcess>,
122    /// Original destination address.
123    pub destination: String,
124    /// Destination host recovered by ingress.
125    pub destination_host: Option<String>,
126    /// TLS SNI, when present.
127    pub server_name: Option<String>,
128    /// Request authority.
129    pub authority: Option<String>,
130    /// Credential-free next-hop proxy authority.
131    pub proxy_endpoint: Option<String>,
132    /// HTTP request or upgrade method.
133    pub method: String,
134    /// HTTP path and query.
135    pub path: String,
136    /// Whether content is a complete WebSocket data message.
137    pub websocket: bool,
138    /// HTTP request number (1) or client data-message number within this flow.
139    pub sequence: u64,
140    /// Original WebSocket type; null for HTTP, including upgrade requests.
141    pub message_type: Option<RequestMessageType>,
142    /// Headers as name/value pairs, preserving duplicates. Headers recognized by
143    /// the MITM credential-header predicate are omitted.
144    pub headers: Vec<(String, String)>,
145    /// Complete decoded content.
146    pub body: DecodedContent,
147    /// Complete parsed JSON when present, including unrecognized fields.
148    pub json: Option<Value>,
149    /// Projection outcome, also supplied for unknown requests.
150    pub parsing_status: RequestParsingStatus,
151    /// Available request-side Harness identity and declarations.
152    pub harness: Option<RequestHarness>,
153    /// Selected model-service credential, without its authentication scheme prefix.
154    pub auth_token: Option<String>,
155    /// Whether token actions can be applied at this forwarding boundary.
156    pub auth_token_writable: bool,
157    /// Whether model actions have a supported protocol write-back location.
158    pub model_writable: bool,
159    /// Known Agent request projection.
160    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/// Plugin reply correlated to one inspection on this connection.
174#[derive(Debug, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct InspectResponse {
177    /// Broker request identifier from the inspection context.
178    pub request_id: String,
179    /// Explicit forwarding decision and optional semantic actions.
180    pub decision: RequestDecision,
181}
182
183/// Semantic edits supported by the broker; values are never included in Debug.
184#[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    /// Set the credential selected by the target's authentication binding.
194    SetAuthToken(String),
195    /// Remove the selected credential.
196    RemoveAuthToken,
197    /// Set the requested model without changing the target or protocol.
198    SetModel(String),
199    /// Remove the model member, including an explicit null.
200    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/// Decision returned by SDK request handlers. Context remains read-only.
238#[derive(Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum RequestDecision {
241    /// Continue without editing the current request.
242    Allow,
243    /// Reject this request with a safe explanation.
244    Block(String),
245    /// Apply the ordered actions before invoking the next plugin.
246    Modify(Box<[ModifyAction]>),
247}
248
249impl RequestDecision {
250    /// Encodes a handler decision for its original request.
251    #[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}