conversation_api/execution/wire/
suggestion.rs1use 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 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 Read { request: FacadeRequest },
33 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
54fn deserialize_closed<'de, D, T>(deserializer: D) -> Result<T, D::Error>
57where
58 D: serde::Deserializer<'de>,
59 T: serde::de::DeserializeOwned,
60{
61 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 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}