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: serde::de::DeserializeOwned,
60{
61    // Restore JSON numbers from Serde's buffered representation before decoding
62    // typed fields. With serde_json/arbitrary_precision, buffered decimals are
63    // maps that a typed f64 visitor cannot consume directly. Value understands
64    // that representation and retains precision for JSON data.
65    let json = Value::deserialize(deserializer)?;
66    let mut unknown = None;
67    let value = serde_ignored::deserialize(json, |path| {
68        unknown.get_or_insert_with(|| path.to_string());
69    })
70    .map_err(serde::de::Error::custom)?;
71    match unknown {
72        Some(path) => Err(serde::de::Error::custom(format!(
73            "unknown protocol field: {path}"
74        ))),
75        None => Ok(value),
76    }
77}
78
79impl SuggestionMessage {
80    /// Validates transport shape, never the sender's authority or registered result type.
81    /// # Errors
82    /// Rejects malformed execution identity and non-object document payloads.
83    pub fn validate(&self) -> Result<(), ProtocolError> {
84        self.context
85            .validate()
86            .map_err(|e| ProtocolError::InvalidBinding(e.into()))?;
87        match &self.payload {
88            SuggestionPayload::Generate {
89                input, llm_plan, ..
90            } => {
91                if !input.is_object() {
92                    return Err(ProtocolError::InvalidBinding(
93                        "Suggestion input must be an object".into(),
94                    ));
95                }
96                super::validate_llm_plan(llm_plan)
97            }
98            SuggestionPayload::Completed { result, .. } if !result.is_object() => Err(
99                ProtocolError::InvalidBinding("Suggestion result must be an object".into()),
100            ),
101            _ => Ok(()),
102        }
103    }
104}