Skip to main content

conversation_api/execution/wire/
suggestion.rs

1//! Non-conversation messages carried by the existing authenticated Agent link.
2//! Payload documents are validated by the registered Suggestion input/output
3//! models at each host. This leaf transport never depends on app-facade-api.
4use super::{LlmExecutionPlan, ProtocolError};
5use crate::execution::{
6    ExternalError, FacadeRequest, OperationalContext, SuggestionInvocationContext, UsageSummary,
7};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct SuggestionMessage {
14    pub context: SuggestionInvocationContext,
15    pub payload: SuggestionPayload,
16}
17
18#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
19#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
20pub enum SuggestionPayload {
21    /// Trusted admission snapshot; never decoded from a public generate input.
22    Generate {
23        input: Value,
24        #[serde(deserialize_with = "deserialize_closed")]
25        facts: OperationalContext,
26        #[serde(deserialize_with = "deserialize_closed")]
27        llm_plan: Box<LlmExecutionPlan>,
28    },
29    #[serde(deserialize_with = "crate::execution::deserialize_empty_variant")]
30    Cancel,
31    /// Only authorized reads and script verification are permitted by the host.
32    Read { request: FacadeRequest },
33    /// Verified typed generation output, not a model-authored completion status.
34    Completed {
35        result: Value,
36        failures: Vec<SuggestionFailure>,
37        #[serde(deserialize_with = "deserialize_closed")]
38        usage: UsageSummary,
39    },
40    Failed {
41        #[serde(deserialize_with = "deserialize_closed")]
42        error: ExternalError,
43    },
44}
45
46#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct SuggestionFailure {
49    pub candidate_index: Option<usize>,
50    #[serde(deserialize_with = "deserialize_closed")]
51    pub error: ExternalError,
52}
53
54// Internally tagged enums buffer their contents before deserializing fields, so
55// the envelope's outer serde_ignored visitor cannot observe these nested maps.
56fn deserialize_closed<'de, D, T>(deserializer: D) -> Result<T, D::Error>
57where
58    D: serde::Deserializer<'de>,
59    T: Deserialize<'de>,
60{
61    let mut unknown = None;
62    let value = serde_ignored::deserialize(deserializer, |path| {
63        unknown.get_or_insert_with(|| path.to_string());
64    })?;
65    match unknown {
66        Some(path) => Err(serde::de::Error::custom(format!(
67            "unknown protocol field: {path}"
68        ))),
69        None => Ok(value),
70    }
71}
72
73impl SuggestionMessage {
74    /// Validates transport shape, never the sender's authority or registered result type.
75    /// # Errors
76    /// Rejects malformed execution identity and non-object document payloads.
77    pub fn validate(&self) -> Result<(), ProtocolError> {
78        self.context
79            .validate()
80            .map_err(|e| ProtocolError::InvalidBinding(e.into()))?;
81        match &self.payload {
82            SuggestionPayload::Generate {
83                input, llm_plan, ..
84            } => {
85                if !input.is_object() {
86                    return Err(ProtocolError::InvalidBinding(
87                        "Suggestion input must be an object".into(),
88                    ));
89                }
90                super::validate_llm_plan(llm_plan)
91            }
92            SuggestionPayload::Completed { result, .. } if !result.is_object() => Err(
93                ProtocolError::InvalidBinding("Suggestion result must be an object".into()),
94            ),
95            _ => Ok(()),
96        }
97    }
98}