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