Skip to main content

muse_code_sdk/
approval.rs

1//! Approval handler routing.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use crate::msp::ApprovalRequestParams;
8
9/// The caller's answer to one server-authored approval request.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct ApprovalDecisionInput {
12    /// One of the choice ids the request offers. Any other is refused: the
13    /// session sends the offered `Denied` choice, else the offered `Abort`
14    /// choice, and fails the approval's turn with a `MuseError::Protocol`
15    /// carrying the [`ApprovalRoutingError::UnofferedChoice`] message once the
16    /// host accepts that answer, or at once when neither is offered. For a
17    /// stage the session already knows the host resolved or moved past, it
18    /// sends nothing and fails no turn, and a `-32051` or `-32053` reply to
19    /// the rejecting choice fails none either. An approval the session already
20    /// retired for its own fault is not one the host moved past: its turn
21    /// fails at once, unless the session has already received the host's
22    /// resolution, and if that fault comes while the rejecting choice is out,
23    /// a `-32053` reply fails it too.
24    pub choice_id: String,
25    /// Free-text guidance delivered to the model with the decision, never
26    /// stored durably. Set it only on a choice whose `accepts_feedback` is
27    /// true: on any other choice the SDK refuses the decision before sending
28    /// it, as it does an unoffered choice. The session sends the offered
29    /// `Denied` choice, else the offered `Abort` choice, and nothing when
30    /// neither is offered, and the approval's turn fails with a
31    /// `MuseError::Protocol` carrying the
32    /// [`ApprovalRoutingError::FeedbackNotAccepted`] message when and as
33    /// `choice_id` says an unoffered choice's turn fails.
34    pub feedback: Option<String>,
35}
36
37type ApprovalHandlerFuture = Pin<Box<dyn Future<Output = ApprovalDecisionInput> + Send + 'static>>;
38type ApprovalHandler =
39    Arc<dyn Fn(ApprovalRequestParams) -> ApprovalHandlerFuture + Send + Sync + 'static>;
40
41/// A local approval decision that cannot be submitted safely.
42///
43/// New refusals may be added, so a `match` on this enum needs a catch-all arm.
44#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
45#[non_exhaustive]
46pub enum ApprovalRoutingError {
47    /// The handler picked a choice the request did not offer.
48    #[error(
49        "approval {approval_id} handler selected unoffered choice {choice_id}; offered choices: {available_choice_ids:?}"
50    )]
51    UnofferedChoice {
52        /// The approval the handler answered.
53        approval_id: String,
54        /// The choice the handler picked.
55        choice_id: String,
56        /// The choices the request offered.
57        available_choice_ids: Vec<String>,
58    },
59    /// The handler attached feedback to a choice that does not accept it.
60    #[error(
61        "{}",
62        feedback_not_accepted(approval_id, choice_id, feedback_choice_ids)
63    )]
64    FeedbackNotAccepted {
65        /// The approval the handler answered.
66        approval_id: String,
67        /// The choice the handler picked.
68        choice_id: String,
69        /// The offered choices that accept feedback.
70        feedback_choice_ids: Vec<String>,
71    },
72}
73
74/// Says what happened and what the handler can do instead: the host refuses
75/// feedback on this choice, so the SDK never sends the decision.
76fn feedback_not_accepted(approval_id: &str, choice_id: &str, accepting: &[String]) -> String {
77    let instead = if accepting.is_empty() {
78        "answer without feedback; no offered choice accepts it".to_owned()
79    } else {
80        format!("answer without feedback, or put it on one of {accepting:?}")
81    };
82    format!(
83        "approval {approval_id}: the handler's choice {choice_id} does not accept feedback, so the SDK did not send that decision and the session answers with the offered rejecting choice, if any; next time, {instead}"
84    )
85}
86
87/// Routes approval requests to one replaceable caller handler.
88#[derive(Default, Clone)]
89pub struct ApprovalRouter {
90    handler: Option<ApprovalHandler>,
91}
92
93impl ApprovalRouter {
94    /// A router with no handler yet: [`Self::route`] answers `Ok(None)`.
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// Replaces the current handler. One request must never race two answers.
100    pub fn on_approval<Handler, HandlerFuture>(&mut self, handler: Handler)
101    where
102        Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
103        HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
104    {
105        self.handler = Some(Arc::new(move |request| Box::pin(handler(request))));
106    }
107
108    /// Returns a validated caller decision, or `None` when no handler is registered.
109    /// The session then sends the server-offered `Denied` choice, else the offered
110    /// `Abort` choice, or fails only that turn when neither is offered.
111    pub async fn route(
112        &self,
113        request: &ApprovalRequestParams,
114    ) -> Result<Option<ApprovalDecisionInput>, ApprovalRoutingError> {
115        let Some(handler) = &self.handler else {
116            return Ok(None);
117        };
118
119        let decision = handler(request.clone()).await;
120        let Some(choice) = request
121            .available_choices
122            .iter()
123            .find(|choice| choice.choice_id == decision.choice_id)
124        else {
125            let available_choice_ids = request
126                .available_choices
127                .iter()
128                .map(|choice| choice.choice_id.clone())
129                .collect();
130            return Err(ApprovalRoutingError::UnofferedChoice {
131                approval_id: request.approval_id.clone(),
132                choice_id: decision.choice_id,
133                available_choice_ids,
134            });
135        };
136        // The host refuses feedback on any other choice and keeps its approval
137        // open, so refuse it here, where the session can still answer.
138        if decision.feedback.is_some() && !choice.accepts_feedback {
139            let feedback_choice_ids = request
140                .available_choices
141                .iter()
142                .filter(|choice| choice.accepts_feedback)
143                .map(|choice| choice.choice_id.clone())
144                .collect();
145            return Err(ApprovalRoutingError::FeedbackNotAccepted {
146                approval_id: request.approval_id.clone(),
147                choice_id: decision.choice_id,
148                feedback_choice_ids,
149            });
150        }
151        Ok(Some(decision))
152    }
153}