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    /// Generate a draft for one authorized adoption, never save it in the worker.
30    Adopt {
31        input: Value,
32        #[serde(deserialize_with = "deserialize_closed")]
33        facts: OperationalContext,
34        #[serde(deserialize_with = "deserialize_closed")]
35        llm_plan: Box<LlmExecutionPlan>,
36    },
37    #[serde(deserialize_with = "crate::execution::deserialize_empty_variant")]
38    Cancel,
39    /// Only authorized reads and script verification are permitted by the host.
40    Read { request: FacadeRequest },
41    /// Verified typed generation output, not a model-authored completion status.
42    Completed {
43        result: Value,
44        failures: Vec<SuggestionFailure>,
45        #[serde(deserialize_with = "deserialize_closed")]
46        usage: UsageSummary,
47    },
48    Failed {
49        #[serde(deserialize_with = "deserialize_closed")]
50        error: ExternalError,
51    },
52}
53
54#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct SuggestionFailure {
57    pub candidate_index: Option<usize>,
58    #[serde(deserialize_with = "deserialize_closed")]
59    pub error: ExternalError,
60}
61
62// Internally tagged enums buffer their contents before deserializing fields, so
63// the envelope's outer serde_ignored visitor cannot observe these nested maps.
64fn deserialize_closed<'de, D, T>(deserializer: D) -> Result<T, D::Error>
65where
66    D: serde::Deserializer<'de>,
67    T: serde::de::DeserializeOwned,
68{
69    // Restore JSON numbers from Serde's buffered representation before decoding
70    // typed fields. With serde_json/arbitrary_precision, buffered decimals are
71    // maps that a typed f64 visitor cannot consume directly. Value understands
72    // that representation and retains precision for JSON data.
73    let json = Value::deserialize(deserializer)?;
74    let mut unknown = None;
75    let value = serde_ignored::deserialize(json, |path| {
76        unknown.get_or_insert_with(|| path.to_string());
77    })
78    .map_err(serde::de::Error::custom)?;
79    match unknown {
80        Some(path) => Err(serde::de::Error::custom(format!(
81            "unknown protocol field: {path}"
82        ))),
83        None => Ok(value),
84    }
85}
86
87impl SuggestionMessage {
88    /// Validates transport shape, never the sender's authority or registered result type.
89    /// # Errors
90    /// Rejects malformed execution identity and non-object document payloads.
91    pub fn validate(&self) -> Result<(), ProtocolError> {
92        self.context
93            .validate()
94            .map_err(|e| ProtocolError::InvalidBinding(e.into()))?;
95        let adoption = matches!(
96            self.context.trigger,
97            crate::execution::SuggestionTrigger::Adoption { .. }
98        );
99        if matches!(self.payload, SuggestionPayload::Adopt { .. }) && !adoption
100            || matches!(self.payload, SuggestionPayload::Generate { .. }) && adoption
101        {
102            return Err(ProtocolError::InvalidBinding(
103                "Suggestion operation does not match its authority".into(),
104            ));
105        }
106        match &self.payload {
107            SuggestionPayload::Generate {
108                input, llm_plan, ..
109            }
110            | SuggestionPayload::Adopt {
111                input, llm_plan, ..
112            } => {
113                if !input.is_object() {
114                    return Err(ProtocolError::InvalidBinding(
115                        "Suggestion input must be an object".into(),
116                    ));
117                }
118                super::validate_llm_plan(llm_plan)
119            }
120            SuggestionPayload::Completed { result, .. } if !result.is_object() => Err(
121                ProtocolError::InvalidBinding("Suggestion result must be an object".into()),
122            ),
123            _ => Ok(()),
124        }
125    }
126}