Skip to main content

aither_agent/
ask_user.rs

1//! Ask-user tool for UI-mediated choice prompts.
2
3use std::borrow::Cow;
4
5use aither_core::llm::tool::{Tool, ToolResult};
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use crate::tool_request::{
10    ToolRequest, ToolRequestBroker, ToolRequestQueue, channel as tool_request_channel,
11};
12
13/// A single question within an `ask_user` request.
14#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
15pub struct Question {
16    /// Short section label for navigation (e.g. "database", "theme").
17    pub section: String,
18    /// The question text to display.
19    pub question: String,
20    /// Options to choose from.
21    #[serde(alias = "options")]
22    pub option: Vec<String>,
23    /// Allow selecting multiple options.
24    #[serde(default)]
25    pub multi_select: bool,
26}
27
28/// Ask the user one or more questions with predefined options.
29///
30/// Displays an interactive prompt where the user picks from options,
31/// types a custom answer, or skips the question.
32///
33/// # Single question (simple form)
34///
35/// ```bash
36/// ask_user "Which database?" --option PostgreSQL --option MySQL --option SQLite
37/// ```
38///
39/// # Multiple questions (use --questions with JSON)
40///
41/// ```bash
42/// ask_user --questions '[
43///   {"section":"database","question":"Which DB?","option":["PostgreSQL","MySQL","SQLite"]},
44///   {"section":"theme","question":"Color theme?","option":["Light","Dark","System"]}
45/// ]'
46/// ```
47#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
48pub struct AskUserArgs {
49    /// The question to ask (for single-question mode).
50    #[serde(default)]
51    pub question: Option<String>,
52    /// Option to choose from (use --option flag for each, repeatable).
53    #[serde(default, alias = "options", alias = "choices")]
54    pub option: Vec<String>,
55    /// Allow selecting multiple options (for single-question mode).
56    #[serde(default)]
57    pub multi_select: bool,
58    /// Multiple questions (JSON array). Overrides `question/options/multi_select` if set.
59    #[serde(default)]
60    pub questions: Vec<Question>,
61}
62
63impl AskUserArgs {
64    /// Normalize into a list of questions.
65    /// If `questions` is non-empty, use that directly.
66    /// Otherwise, build a single question from the flat fields.
67    #[must_use]
68    pub fn into_questions(self) -> Vec<Question> {
69        if !self.questions.is_empty() {
70            return self.questions;
71        }
72        if let Some(q) = self.question {
73            vec![Question {
74                section: String::new(),
75                question: q,
76                option: self.option,
77                multi_select: self.multi_select,
78            }]
79        } else {
80            Vec::new()
81        }
82    }
83}
84
85/// The user's answer to a single question.
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct QuestionAnswer {
88    /// Section label (matches `Question::section`).
89    pub section: String,
90    /// Selected option values, or custom text.
91    pub answer: AnswerValue,
92}
93
94/// Possible answer values.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96#[serde(untagged)]
97pub enum AnswerValue {
98    /// User selected from predefined options.
99    Selected(Vec<String>),
100    /// User typed a custom answer.
101    Custom(String),
102    /// User skipped this question.
103    Skipped,
104}
105
106/// A request from the agent to ask the user questions.
107pub type AskUserRequest = ToolRequest<AskUserRequestPayload, Vec<QuestionAnswer>>;
108
109/// Internal request payload sent from a session-bound tool to the host runtime.
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct AskUserRequestPayload {
112    /// Session issuing the request.
113    pub session_id: String,
114    /// User-visible request body.
115    pub request: AskUserArgs,
116}
117
118/// Broker for `ask_user` requests.
119pub type AskUserBroker = ToolRequestBroker<AskUserRequestPayload, Vec<QuestionAnswer>>;
120
121/// Queue for pending `ask_user` requests.
122pub type AskUserQueue = ToolRequestQueue<AskUserRequestPayload, Vec<QuestionAnswer>>;
123
124/// Create a new `ask_user` channel pair.
125#[must_use]
126pub fn channel() -> (AskUserBroker, AskUserQueue) {
127    tool_request_channel()
128}
129
130/// Tool implementation for asking the user questions.
131#[derive(Debug, Clone)]
132pub struct AskUserTool {
133    broker: AskUserBroker,
134    session_id: String,
135}
136
137impl AskUserTool {
138    /// Create a new `AskUserTool` with the given sender.
139    #[must_use]
140    pub fn new(session_id: impl Into<String>, broker: AskUserBroker) -> Self {
141        Self {
142            broker,
143            session_id: session_id.into(),
144        }
145    }
146}
147
148impl Tool for AskUserTool {
149    fn name(&self) -> Cow<'static, str> {
150        "ask_user".into()
151    }
152
153    type Arguments = AskUserArgs;
154    type Res = ToolResult;
155
156    async fn call(&self, args: Self::Arguments) -> aither_core::Result<Self::Res> {
157        let response = self
158            .broker
159            .request(AskUserRequestPayload {
160                session_id: self.session_id.clone(),
161                request: args,
162            })
163            .await?;
164        ToolResult::json(&response)
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn test_deser_option_array() {
174        let json = serde_json::json!({
175            "question": "请选择你喜欢的水果?",
176            "option": ["苹果", "香蕉", "橘子", "梨"]
177        });
178        let args: AskUserArgs = serde_json::from_value(json).unwrap();
179        assert_eq!(args.option.len(), 4);
180        assert_eq!(args.option, vec!["苹果", "香蕉", "橘子", "梨"]);
181        let questions = args.into_questions();
182        assert_eq!(questions.len(), 1);
183        assert_eq!(questions[0].option.len(), 4);
184    }
185
186    #[test]
187    fn test_schema_option_is_array() {
188        let schema = schemars::schema_for!(AskUserArgs);
189        let val = serde_json::to_value(schema).unwrap();
190        tracing::debug!(
191            "AskUserArgs schema:\n{}",
192            serde_json::to_string_pretty(&val).unwrap()
193        );
194
195        let props = val.get("properties").unwrap().as_object().unwrap();
196        let opt = props.get("option").unwrap();
197        tracing::debug!(
198            "option field schema: {}",
199            serde_json::to_string_pretty(opt).unwrap()
200        );
201
202        let opt_type = opt.get("type").and_then(|t| t.as_str());
203        assert_eq!(
204            opt_type,
205            Some("array"),
206            "option must be array type in schema"
207        );
208    }
209
210    #[test]
211    fn test_cli_to_json_with_real_schema() {
212        let schema = schemars::schema_for!(AskUserArgs);
213        let schema_val = serde_json::to_value(schema).unwrap();
214
215        let result = aither_sandbox::cli_to_json(
216            &schema_val,
217            &[
218                "--question".into(),
219                "请选择你喜欢的水果?".into(),
220                "--option".into(),
221                "苹果".into(),
222                "--option".into(),
223                "香蕉".into(),
224                "--option".into(),
225                "橘子".into(),
226                "--option".into(),
227                "梨".into(),
228            ],
229        )
230        .unwrap();
231
232        tracing::debug!(
233            "cli_to_json result: {}",
234            serde_json::to_string_pretty(&result).unwrap()
235        );
236
237        let args: AskUserArgs = serde_json::from_value(result).unwrap();
238        assert_eq!(
239            args.option.len(),
240            4,
241            "expected 4 options, got: {:?}",
242            args.option
243        );
244        assert_eq!(args.option, vec!["苹果", "香蕉", "橘子", "梨"]);
245    }
246}