Skip to main content

base/interface/
elicitation.rs

1//! `Elicitation` — the one way the engine asks a human something.
2//!
3//! Three questions in this engine need a person: may this tool call proceed,
4//! what did you mean, and shall I import the configuration I found. Each grew
5//! its own mechanism — a channel protocol for the first, a process-level
6//! callback trait for the third, and for the second a tool that hands its own
7//! question back to the model and calls that an answer. A host wanting to
8//! answer all three had to learn all three, and a host that could answer none
9//! of them got a different failure from each.
10//!
11//! # Silence is not consent
12//!
13//! With no implementation registered, every kind of question is *declined*
14//! with a reason, never granted. That is the whole reason this is a trait with
15//! a default rather than an `Option` each caller interprets: the fallback is
16//! written once, here, and it fails closed.
17//!
18//! # Why the answer is a `Value`
19//!
20//! The three questions have genuinely different answers — a permission
21//! decision, a chosen option or free text, an import choice — and a trait
22//! object cannot be generic over them. So the payload is serde-shaped and
23//! [`ElicitKind`] documents which type belongs to it. Every call site parses
24//! with the type it expects and treats a parse failure exactly like a
25//! decline, which keeps a confused implementation from being read as consent.
26
27use std::path::PathBuf;
28use std::sync::Arc;
29
30use async_trait::async_trait;
31use serde::de::DeserializeOwned;
32use serde::{Deserialize, Serialize};
33
34/// What is being asked, and how the answer will be read.
35#[derive(Debug, Clone, PartialEq, Eq)]
36#[non_exhaustive]
37pub enum ElicitKind {
38    /// May this tool call run? The answer is the host's permission decision
39    /// (`runtime::agent::PermissionDecision`'s wire form).
40    Authorization {
41        tool_name: String,
42        /// Paths the call would touch, for a host that wants to show them.
43        paths: Vec<PathBuf>,
44        /// The `tool_use` block asking, when the asker knows it.
45        tool_use_id: Option<String>,
46        /// The plugin command whose call it is; `None` for the model's own.
47        origin: Option<PromptOrigin>,
48    },
49    /// The model wants something clarified before it continues. The answer is
50    /// either one of the request's option keys or free text, as a JSON string.
51    Clarification {
52        /// Short label for the question, for a host with room for one.
53        header: Option<String>,
54        /// The `tool_use` block asking, when the asker knows it.
55        tool_use_id: Option<String>,
56    },
57    /// Shall configuration detected from another agent tool be imported? The
58    /// answer is yes or no.
59    Import {
60        /// The detected sources, named for display.
61        sources: Vec<String>,
62    },
63    /// An MCP server asks the user something during one of its tool calls.
64    /// Its message, schema and URL are the server's words, not the engine's.
65    /// The answer is a [`McpElicitationAnswer`].
66    McpServer {
67        server: String,
68        mode: McpElicitMode,
69        tool_use_id: Option<String>,
70        /// The engine cut the server's message down to fit.
71        limited: bool,
72    },
73}
74
75/// The `RunExt` call a sub-call belongs to: what a host answering for the
76/// command, not for the model, judges by.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
78pub struct PromptOrigin {
79    /// `RunExt:<command>`, as `tool.around` is told.
80    pub via: String,
81    /// The `RunExt` call's own `tool_use` id.
82    pub tool_use_id: String,
83    /// The command line it ran.
84    pub command: String,
85}
86
87/// What an MCP server's question wants back.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum McpElicitMode {
90    /// Fields to fill in, described by a JSON Schema the server sent.
91    Form { requested_schema: serde_json::Value },
92    /// A page for the user to visit; nothing comes back but the choice.
93    /// `host` is `url`'s, for a host that shows where the link goes.
94    Url { url: String, host: String },
95}
96
97/// The answer to [`ElicitKind::McpServer`], as it goes back to the server.
98/// `decline` is a person saying no; `cancel` is nobody choosing.
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
100#[serde(tag = "type", rename_all = "snake_case")]
101pub enum McpElicitationAnswer {
102    Accept {
103        #[serde(default, skip_serializing_if = "Option::is_none")]
104        content: Option<serde_json::Value>,
105    },
106    Decline,
107    Cancel,
108}
109
110impl McpElicitationAnswer {
111    pub fn action(&self) -> &'static str {
112        match self {
113            Self::Accept { .. } => "accept",
114            Self::Decline => "decline",
115            Self::Cancel => "cancel",
116        }
117    }
118}
119
120/// One offered answer.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct ElicitOption {
123    /// What the answer carries if this one is picked.
124    pub key: String,
125    /// What the human reads.
126    pub label: String,
127}
128
129/// One question put to a human.
130#[derive(Debug, Clone)]
131pub struct ElicitRequest {
132    /// Correlates the answer with the question for hosts whose transport is
133    /// asynchronous. Unique within a session.
134    pub id: String,
135    pub kind: ElicitKind,
136    /// The question itself, already phrased for a person.
137    pub message: String,
138    /// Offered answers. Empty means free-form.
139    pub options: Vec<ElicitOption>,
140    /// The asking sub-agent's session, the deepest when delegations nest.
141    pub agent_session_id: Option<String>,
142}
143
144/// What came back.
145#[derive(Debug, Clone, PartialEq)]
146pub enum ElicitOutcome {
147    /// A human answered. The shape is [`ElicitKind`]'s to define.
148    Answered(serde_json::Value),
149    /// Nobody answered, or the answer was no. Always carries a reason: a
150    /// caller that has to explain a refusal to a model, a log or a user
151    /// should never have to invent one.
152    Declined { reason: String },
153}
154
155impl ElicitOutcome {
156    /// An answer, from whatever type the request's kind calls for.
157    pub fn answered<T: Serialize>(answer: &T) -> Self {
158        match serde_json::to_value(answer) {
159            Ok(v) => Self::Answered(v),
160            // Only reachable if a kind's answer type is not serializable,
161            // which is a bug in the caller — but declining is still the safe
162            // reading of "we could not produce an answer".
163            Err(e) => Self::Declined {
164                reason: format!("the answer could not be encoded: {e}"),
165            },
166        }
167    }
168
169    pub fn declined(reason: impl Into<String>) -> Self {
170        Self::Declined {
171            reason: reason.into(),
172        }
173    }
174
175    /// Read the answer as the type this request's kind defines.
176    ///
177    /// `None` for a decline **and** for an answer that does not parse — a
178    /// caller cannot act on an answer it does not understand, and guessing
179    /// would be guessing about consent.
180    pub fn answer_as<T: DeserializeOwned>(&self) -> Option<T> {
181        match self {
182            Self::Answered(v) => serde_json::from_value(v.clone()).ok(),
183            Self::Declined { .. } => None,
184        }
185    }
186
187    /// The reason a question went unanswered, for a caller reporting it.
188    pub fn decline_reason(&self) -> Option<&str> {
189        match self {
190            Self::Declined { reason } => Some(reason),
191            Self::Answered(_) => None,
192        }
193    }
194}
195
196/// The host's ability to ask a person something.
197#[async_trait]
198pub trait Elicitation: Send + Sync {
199    /// Put `request` to a human and return their answer.
200    ///
201    /// May take as long as a person takes; callers impose their own timeout
202    /// and cancellation. Implementations that cannot serve a particular
203    /// [`ElicitKind`] must decline it with a reason rather than answer it
204    /// wrongly — a host wired only for permission prompts saying "declined:
205    /// this host has no way to ask" is useful, and one inventing an answer
206    /// is not.
207    async fn ask(&self, request: ElicitRequest) -> ElicitOutcome;
208
209    /// [`ask`](Self::ask), given up on once `within` has passed with no
210    /// answer: `None` then. `within: None` waits as long as `ask` does.
211    ///
212    /// An implementation whose answers arrive from elsewhere should override
213    /// this so the deadline and an answer cannot both win: one answer that
214    /// lands as the deadline passes is either taken or refused, never taken
215    /// and reported as not taken.
216    async fn ask_within(
217        &self,
218        request: ElicitRequest,
219        within: Option<std::time::Duration>,
220    ) -> Option<ElicitOutcome> {
221        match within {
222            None => Some(self.ask(request).await),
223            Some(within) => tokio::time::timeout(within, self.ask(request)).await.ok(),
224        }
225    }
226
227    /// Whether a clarification asked here can reach a person. A session
228    /// whose elicitation cannot carry one is not offered `AskUserQuestion`.
229    fn can_clarify(&self) -> bool {
230        true
231    }
232}
233
234/// Declines everything, with a reason naming the absence.
235///
236/// The default when no host registered anything. Every path that asks a human
237/// gets an explicit refusal instead of hanging, timing out, or — the failure
238/// this exists to prevent — treating silence as a yes.
239pub struct DeclineAll;
240
241#[async_trait]
242impl Elicitation for DeclineAll {
243    async fn ask(&self, request: ElicitRequest) -> ElicitOutcome {
244        let what = match &request.kind {
245            ElicitKind::Authorization { tool_name, .. } => {
246                format!("authorize `{tool_name}`")
247            }
248            ElicitKind::Clarification { .. } => "answer a question".to_string(),
249            ElicitKind::Import { .. } => "confirm an import".to_string(),
250            ElicitKind::McpServer { server, .. } => format!("answer MCP server `{server}`"),
251        };
252        ElicitOutcome::declined(format!(
253            "no one is available to {what}: this engine was built without an \
254             elicitation handler, and an unanswered question is not consent"
255        ))
256    }
257}
258
259/// Answers every question the same way, and remembers what it was asked.
260///
261/// For tests, and as the shape an embedder copies: the second implementation
262/// that makes [`Elicitation`] a contract rather than one type's interface.
263pub struct FixedElicitation {
264    answer: ElicitOutcome,
265    asked: std::sync::Mutex<Vec<ElicitRequest>>,
266}
267
268impl FixedElicitation {
269    pub fn new(answer: ElicitOutcome) -> Arc<Self> {
270        Arc::new(Self {
271            answer,
272            asked: std::sync::Mutex::new(Vec::new()),
273        })
274    }
275
276    /// Every request put to it, in order.
277    pub fn asked(&self) -> Vec<ElicitRequest> {
278        self.asked.lock().unwrap_or_else(|e| e.into_inner()).clone()
279    }
280}
281
282#[async_trait]
283impl Elicitation for FixedElicitation {
284    async fn ask(&self, request: ElicitRequest) -> ElicitOutcome {
285        self.asked
286            .lock()
287            .unwrap_or_else(|e| e.into_inner())
288            .push(request);
289        self.answer.clone()
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    fn req(kind: ElicitKind) -> ElicitRequest {
298        ElicitRequest {
299            agent_session_id: None,
300            id: "q1".into(),
301            kind,
302            message: "well?".into(),
303            options: vec![],
304        }
305    }
306
307    #[tokio::test]
308    async fn nothing_registered_declines_every_kind_with_a_reason() {
309        let kinds = [
310            ElicitKind::Authorization {
311                tool_name: "Bash".into(),
312                paths: vec![],
313                tool_use_id: None,
314                origin: None,
315            },
316            ElicitKind::Clarification {
317                header: None,
318                tool_use_id: None,
319            },
320            ElicitKind::Import { sources: vec![] },
321        ];
322        for kind in kinds {
323            let out = DeclineAll.ask(req(kind.clone())).await;
324            let reason = out
325                .decline_reason()
326                .unwrap_or_else(|| panic!("{kind:?} must be declined, never answered"));
327            assert!(
328                !reason.trim().is_empty(),
329                "a decline without a reason is a shrug: {kind:?}"
330            );
331        }
332    }
333
334    /// The property the `Value` payload has to earn: an answer that does not
335    /// parse as the kind's type reads as no answer, not as a default one.
336    #[test]
337    fn an_answer_of_the_wrong_shape_is_not_an_answer() {
338        let out = ElicitOutcome::Answered(serde_json::json!({"type": "not-a-decision"}));
339        assert_eq!(out.answer_as::<String>(), None);
340        assert_eq!(
341            ElicitOutcome::answered(&"picked".to_string()).answer_as::<String>(),
342            Some("picked".to_string())
343        );
344    }
345}