| 1 | //! Tool and types for requesting user input via the TUI. |
| 2 | |
| 3 | use super::spec::{ |
| 4 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 5 | }; |
| 6 | use async_trait::async_trait; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use serde_json::{Value, json}; |
| 9 | use std::collections::HashSet; |
| 10 | |
| 11 | /// Default ceiling on `request_user_input.questions` (#5949). Raised from the |
| 12 | /// former hard-coded 3 so research/planning turns that need four or more |
| 13 | /// clarifications are not rejected outright. |
| 14 | pub const DEFAULT_MAX_QUESTIONS: usize = 6; |
| 15 | /// Default ceiling on options per question. |
| 16 | pub const DEFAULT_MAX_OPTIONS: usize = 4; |
| 17 | /// Inclusive bounds a configured `user_input_max_questions` is clamped into. |
| 18 | pub const MIN_CONFIGURABLE_QUESTIONS: usize = 1; |
| 19 | pub const MAX_CONFIGURABLE_QUESTIONS: usize = 10; |
| 20 | /// Inclusive bounds a configured `user_input_max_options` is clamped into. |
| 21 | /// The floor is 2 because a one-option question is not a choice. |
| 22 | pub const MIN_CONFIGURABLE_OPTIONS: usize = 2; |
| 23 | pub const MAX_CONFIGURABLE_OPTIONS: usize = 10; |
| 24 | |
| 25 | /// Config key naming used in both the clamp WARN and the rejection message, so |
| 26 | /// a model that hits the ceiling is told exactly where to raise it. |
| 27 | pub const MAX_QUESTIONS_KEY: &str = "[tools] user_input_max_questions"; |
| 28 | pub const MAX_OPTIONS_KEY: &str = "[tools] user_input_max_options"; |
| 29 | |
| 30 | /// Effective `request_user_input` payload ceilings for one session. |
| 31 | /// |
| 32 | /// Resolved once from `[tools]` in config.toml (see |
| 33 | /// [`UserInputLimits::from_config`]) and carried to the three |
| 34 | /// places that must agree: the validator, the tool's JSON schema, and its |
| 35 | /// model-visible description. |
| 36 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 37 | pub struct UserInputLimits { |
| 38 | pub max_questions: usize, |
| 39 | pub max_options: usize, |
| 40 | } |
| 41 | |
| 42 | impl Default for UserInputLimits { |
| 43 | fn default() -> Self { |
| 44 | Self { |
| 45 | max_questions: DEFAULT_MAX_QUESTIONS, |
| 46 | max_options: DEFAULT_MAX_OPTIONS, |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl UserInputLimits { |
| 52 | /// Effective `request_user_input` payload ceilings for this session |
| 53 | /// (#5949). Resolved once per engine build; out-of-range `[tools]` values |
| 54 | /// clamp with a single warning naming the key and the value used. |
| 55 | #[must_use] |
| 56 | pub fn from_config(config: &codewhale_runtime::config::Config) -> Self { |
| 57 | let tools = config.tools.as_ref(); |
| 58 | Self::from_config_values( |
| 59 | tools.and_then(|t| t.user_input_max_questions), |
| 60 | tools.and_then(|t| t.user_input_max_options), |
| 61 | ) |
| 62 | } |
| 63 | |
| 64 | /// Resolve raw `[tools]` values, clamping each into its supported range. |
| 65 | /// An out-of-range value is honoured as far as it can be rather than |
| 66 | /// failing the load, and says so once with the key and the value used. |
| 67 | #[must_use] |
| 68 | pub fn from_config_values(max_questions: Option<u32>, max_options: Option<u32>) -> Self { |
| 69 | Self { |
| 70 | max_questions: clamp_with_warn( |
| 71 | max_questions, |
| 72 | DEFAULT_MAX_QUESTIONS, |
| 73 | MIN_CONFIGURABLE_QUESTIONS, |
| 74 | MAX_CONFIGURABLE_QUESTIONS, |
| 75 | MAX_QUESTIONS_KEY, |
| 76 | ), |
| 77 | max_options: clamp_with_warn( |
| 78 | max_options, |
| 79 | DEFAULT_MAX_OPTIONS, |
| 80 | MIN_CONFIGURABLE_OPTIONS, |
| 81 | MAX_CONFIGURABLE_OPTIONS, |
| 82 | MAX_OPTIONS_KEY, |
| 83 | ), |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | fn clamp_with_warn(raw: Option<u32>, default: usize, min: usize, max: usize, key: &str) -> usize { |
| 89 | let Some(raw) = raw else { |
| 90 | return default; |
| 91 | }; |
| 92 | let raw = raw as usize; |
| 93 | let clamped = raw.clamp(min, max); |
| 94 | if clamped != raw { |
| 95 | tracing::warn!( |
| 96 | "`{key}` = {raw} is outside the supported range {min}..={max}; using {clamped}" |
| 97 | ); |
| 98 | } |
| 99 | clamped |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 103 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 104 | pub struct UserInputOption { |
| 105 | pub label: String, |
| 106 | #[serde(default)] |
| 107 | pub description: String, |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 111 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 112 | #[serde(tag = "kind", rename_all = "kebab-case")] |
| 113 | pub enum UserInputIntent { |
| 114 | PlanReview { |
| 115 | approve: String, |
| 116 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 117 | call_id: Option<String>, |
| 118 | }, |
| 119 | } |
| 120 | |
| 121 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 122 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 123 | pub struct UserInputQuestion { |
| 124 | #[serde(default)] |
| 125 | pub header: String, |
| 126 | pub id: String, |
| 127 | pub question: String, |
| 128 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 129 | pub detail: Option<String>, |
| 130 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 131 | pub intent: Option<UserInputIntent>, |
| 132 | #[serde(default)] |
| 133 | pub options: Vec<UserInputOption>, |
| 134 | /// When `true`, the modal offers a free-text "Other" response in addition |
| 135 | /// to the fixed options. Defaults to `false` for backwards compatibility |
| 136 | /// (older payloads omitting the field get the previous behavior). |
| 137 | #[serde(default)] |
| 138 | pub allow_free_text: bool, |
| 139 | /// When `true`, the user may select more than one option before confirming. |
| 140 | #[serde(default)] |
| 141 | pub multi_select: bool, |
| 142 | } |
| 143 | |
| 144 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 145 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 146 | pub struct UserInputRequest { |
| 147 | #[serde(default)] |
| 148 | pub require_typed_answers: bool, |
| 149 | pub questions: Vec<UserInputQuestion>, |
| 150 | } |
| 151 | |
| 152 | impl UserInputRequest { |
| 153 | /// Parse and validate against the built-in default limits. Call sites that |
| 154 | /// hold a session's resolved config use [`Self::from_value_with_limits`]. |
| 155 | #[cfg(any(test, feature = "test-support"))] |
| 156 | pub fn from_value(value: &Value) -> Result<Self, ToolError> { |
| 157 | Self::from_value_with_limits(value, UserInputLimits::default()) |
| 158 | } |
| 159 | |
| 160 | pub fn from_value_with_limits( |
| 161 | value: &Value, |
| 162 | limits: UserInputLimits, |
| 163 | ) -> Result<Self, ToolError> { |
| 164 | let mut request: UserInputRequest = serde_json::from_value(value.clone()).map_err(|e| { |
| 165 | ToolError::invalid_input(format!("Invalid request_user_input payload: {e}")) |
| 166 | })?; |
| 167 | request.require_typed_answers = false; |
| 168 | request.validate_with_limits(limits)?; |
| 169 | Ok(request) |
| 170 | } |
| 171 | |
| 172 | #[cfg(any(test, feature = "test-support"))] |
| 173 | pub fn validate(&self) -> Result<(), ToolError> { |
| 174 | self.validate_with_limits(UserInputLimits::default()) |
| 175 | } |
| 176 | |
| 177 | pub fn validate_with_limits(&self, limits: UserInputLimits) -> Result<(), ToolError> { |
| 178 | if self.questions.is_empty() { |
| 179 | return Err(ToolError::invalid_input( |
| 180 | "request_user_input.questions must be non-empty", |
| 181 | )); |
| 182 | } |
| 183 | if self.questions.len() > limits.max_questions { |
| 184 | return Err(ToolError::invalid_input(format!( |
| 185 | "request_user_input.questions must contain 1 to {max} items (got {got}); \ |
| 186 | ask the most important {max} now and the rest after the answers. \ |
| 187 | The user can raise the ceiling with `{MAX_QUESTIONS_KEY}` in config.toml \ |
| 188 | (supported range {MIN_CONFIGURABLE_QUESTIONS}..={MAX_CONFIGURABLE_QUESTIONS})", |
| 189 | max = limits.max_questions, |
| 190 | got = self.questions.len(), |
| 191 | ))); |
| 192 | } |
| 193 | for q in &self.questions { |
| 194 | let got = q.options.len(); |
| 195 | if got < MIN_CONFIGURABLE_OPTIONS { |
| 196 | return Err(ToolError::invalid_input(format!( |
| 197 | "request_user_input question `{id}` needs {MIN_CONFIGURABLE_OPTIONS} to {max} options (got {got}); \ |
| 198 | offer at least two concrete choices, recommended first. The user can always type another answer.", |
| 199 | id = q.id, |
| 200 | max = limits.max_options, |
| 201 | ))); |
| 202 | } |
| 203 | if got > limits.max_options { |
| 204 | return Err(ToolError::invalid_input(format!( |
| 205 | "request_user_input question `{id}` allows at most {max} options (got {got}); \ |
| 206 | keep the strongest {max} or split it into two questions. \ |
| 207 | The user can raise the ceiling with `{MAX_OPTIONS_KEY}` in config.toml \ |
| 208 | (supported range {MIN_CONFIGURABLE_OPTIONS}..={MAX_CONFIGURABLE_OPTIONS})", |
| 209 | id = q.id, |
| 210 | max = limits.max_options, |
| 211 | ))); |
| 212 | } |
| 213 | } |
| 214 | self.validate_transport() |
| 215 | } |
| 216 | |
| 217 | pub fn validate_transport(&self) -> Result<(), ToolError> { |
| 218 | if self.questions.is_empty() || self.questions.len() > MAX_CONFIGURABLE_QUESTIONS { |
| 219 | return Err(ToolError::invalid_input( |
| 220 | "User input must contain 1 to 10 questions", |
| 221 | )); |
| 222 | } |
| 223 | if serde_json::to_vec(self) |
| 224 | .map_err(|_| ToolError::invalid_input("Invalid user input request"))? |
| 225 | .len() |
| 226 | > 1024 * 1024 |
| 227 | { |
| 228 | return Err(ToolError::invalid_input("User input request exceeds 1 MiB")); |
| 229 | } |
| 230 | let mut ids = HashSet::new(); |
| 231 | for question in &self.questions { |
| 232 | if question.id.trim().is_empty() |
| 233 | || question.question.trim().is_empty() |
| 234 | || !ids.insert(&question.id) |
| 235 | { |
| 236 | return Err(ToolError::invalid_input( |
| 237 | "User input questions require unique nonempty ids and nonempty text", |
| 238 | )); |
| 239 | } |
| 240 | if question.options.len() > 1000 |
| 241 | || (question.options.is_empty() && !question.allow_free_text) |
| 242 | { |
| 243 | return Err(ToolError::invalid_input( |
| 244 | "User input supports at most 1000 choices per question; zero choices requires free text", |
| 245 | )); |
| 246 | } |
| 247 | let mut labels = HashSet::new(); |
| 248 | for option in &question.options { |
| 249 | if option.label.trim().is_empty() || !labels.insert(&option.label) { |
| 250 | return Err(ToolError::invalid_input( |
| 251 | "User input choices require unique nonempty labels", |
| 252 | )); |
| 253 | } |
| 254 | } |
| 255 | if let Some(UserInputIntent::PlanReview { approve, .. }) = &question.intent |
| 256 | && (!labels.contains(approve) |
| 257 | || question |
| 258 | .detail |
| 259 | .as_ref() |
| 260 | .is_none_or(|detail| detail.trim().is_empty())) |
| 261 | { |
| 262 | return Err(ToolError::invalid_input( |
| 263 | "Plan review requires detail and an offered approve choice", |
| 264 | )); |
| 265 | } |
| 266 | } |
| 267 | Ok(()) |
| 268 | } |
| 269 | |
| 270 | pub fn validate_response(&self, response: &UserInputResponse) -> Result<(), ToolError> { |
| 271 | if response.answers.len() > 10020 |
| 272 | || serde_json::to_vec(response) |
| 273 | .map_err(|_| ToolError::invalid_input("Invalid user input response"))? |
| 274 | .len() |
| 275 | > 1024 * 1024 |
| 276 | { |
| 277 | return Err(ToolError::invalid_input( |
| 278 | "User input response exceeds its transport limits", |
| 279 | )); |
| 280 | } |
| 281 | if response.answers.iter().any(|answer| { |
| 282 | !self |
| 283 | .questions |
| 284 | .iter() |
| 285 | .any(|question| question.id == answer.id) |
| 286 | }) { |
| 287 | return Err(ToolError::invalid_input("Answer names an unknown question")); |
| 288 | } |
| 289 | if !self.require_typed_answers |
| 290 | && response.answers.iter().all(|answer| answer.kind.is_none()) |
| 291 | { |
| 292 | return Ok(()); |
| 293 | } |
| 294 | if response.answers.iter().any(|answer| answer.kind.is_none()) { |
| 295 | return Err(ToolError::invalid_input( |
| 296 | "This question requires typed answers; use a client that supports choice, custom and skipped answers", |
| 297 | )); |
| 298 | } |
| 299 | for question in &self.questions { |
| 300 | let mut choices = HashSet::new(); |
| 301 | let mut custom = false; |
| 302 | let mut skipped = false; |
| 303 | let mut count = 0; |
| 304 | for answer in response |
| 305 | .answers |
| 306 | .iter() |
| 307 | .filter(|answer| answer.id == question.id) |
| 308 | { |
| 309 | count += 1; |
| 310 | match answer.kind { |
| 311 | Some(UserInputAnswerKind::Choice) => { |
| 312 | if answer.label != answer.value |
| 313 | || !question |
| 314 | .options |
| 315 | .iter() |
| 316 | .any(|option| option.label == answer.value) |
| 317 | || !choices.insert(&answer.value) |
| 318 | { |
| 319 | return Err(ToolError::invalid_input( |
| 320 | "Answer must select each offered label at most once", |
| 321 | )); |
| 322 | } |
| 323 | } |
| 324 | Some(UserInputAnswerKind::Custom) => { |
| 325 | if (self.require_typed_answers && !question.allow_free_text) |
| 326 | || custom |
| 327 | || !answer.label.is_empty() |
| 328 | || answer.value.trim().is_empty() |
| 329 | { |
| 330 | return Err(ToolError::invalid_input("Invalid custom answer")); |
| 331 | } |
| 332 | custom = true; |
| 333 | } |
| 334 | Some(UserInputAnswerKind::Skipped) => { |
| 335 | if skipped || !answer.label.is_empty() || !answer.value.is_empty() { |
| 336 | return Err(ToolError::invalid_input("Invalid skipped answer")); |
| 337 | } |
| 338 | skipped = true; |
| 339 | } |
| 340 | None => unreachable!(), |
| 341 | } |
| 342 | } |
| 343 | if count == 0 |
| 344 | || (skipped && count != 1) |
| 345 | || (!question.multi_select && choices.len() + usize::from(custom) > 1) |
| 346 | { |
| 347 | return Err(ToolError::invalid_input( |
| 348 | "Answer must explicitly answer or skip each question and respect single selection", |
| 349 | )); |
| 350 | } |
| 351 | } |
| 352 | Ok(()) |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 357 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 358 | #[serde(rename_all = "snake_case")] |
| 359 | pub enum UserInputAnswerKind { |
| 360 | Choice, |
| 361 | Custom, |
| 362 | Skipped, |
| 363 | } |
| 364 | |
| 365 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 366 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 367 | pub struct UserInputAnswer { |
| 368 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 369 | pub kind: Option<UserInputAnswerKind>, |
| 370 | pub id: String, |
| 371 | pub label: String, |
| 372 | pub value: String, |
| 373 | } |
| 374 | |
| 375 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 376 | #[cfg_attr(test, derive(schemars::JsonSchema))] |
| 377 | pub struct UserInputResponse { |
| 378 | pub answers: Vec<UserInputAnswer>, |
| 379 | } |
| 380 | |
| 381 | pub struct RequestUserInputTool { |
| 382 | limits: UserInputLimits, |
| 383 | /// Rendered once at construction: `description` hands out a borrow, and the |
| 384 | /// effective ceiling only changes when the registry is rebuilt. |
| 385 | description: String, |
| 386 | } |
| 387 | |
| 388 | impl Default for RequestUserInputTool { |
| 389 | fn default() -> Self { |
| 390 | Self::new(UserInputLimits::default()) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | impl RequestUserInputTool { |
| 395 | #[must_use] |
| 396 | pub fn new(limits: UserInputLimits) -> Self { |
| 397 | Self { |
| 398 | description: format!( |
| 399 | "Ask the user 1-{} short multiple-choice questions and return their selections. \ |
| 400 | Use when a decision is the user's and the request, the code and a sensible default cannot settle \ |
| 401 | it. Not for conventional defaults, reversible work, facts you can read, or \"may I continue?\". \ |
| 402 | Put the recommended option first with \"(Recommended)\" in its label; give each option a \ |
| 403 | one-line trade-off. Make each question stand alone; the dialog may be all the user sees. The user \ |
| 404 | can always type another answer. Blocks until answered.", |
| 405 | limits.max_questions |
| 406 | ), |
| 407 | limits, |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | #[async_trait] |
| 413 | impl ToolSpec for RequestUserInputTool { |
| 414 | fn name(&self) -> &'static str { |
| 415 | "request_user_input" |
| 416 | } |
| 417 | |
| 418 | fn description(&self) -> &str { |
| 419 | &self.description |
| 420 | } |
| 421 | |
| 422 | fn input_schema(&self) -> Value { |
| 423 | json!({ |
| 424 | "type": "object", |
| 425 | "properties": { |
| 426 | "questions": { |
| 427 | "type": "array", |
| 428 | "items": { |
| 429 | "type": "object", |
| 430 | "properties": { |
| 431 | "header": { "type": "string", "description": "Chip label, 12 characters or fewer." }, |
| 432 | "id": { "type": "string" }, |
| 433 | "question": { "type": "string", "description": "Standalone question ending in a question mark." }, |
| 434 | "options": { |
| 435 | "type": "array", |
| 436 | "description": format!("{MIN_CONFIGURABLE_OPTIONS}-{} mutually exclusive choices, recommended first.", self.limits.max_options), |
| 437 | "items": { |
| 438 | "type": "object", |
| 439 | "properties": { |
| 440 | "label": { "type": "string" }, |
| 441 | "description": { "type": "string" } |
| 442 | }, |
| 443 | "required": ["label"] |
| 444 | }, |
| 445 | "minItems": MIN_CONFIGURABLE_OPTIONS, |
| 446 | "maxItems": self.limits.max_options |
| 447 | }, |
| 448 | "multi_select": { |
| 449 | "type": "boolean", |
| 450 | "description": "True when several may apply.", |
| 451 | "default": false |
| 452 | } |
| 453 | }, |
| 454 | "required": ["id", "question", "options"] |
| 455 | }, |
| 456 | "minItems": 1, |
| 457 | "maxItems": self.limits.max_questions |
| 458 | } |
| 459 | }, |
| 460 | "required": ["questions"] |
| 461 | }) |
| 462 | } |
| 463 | |
| 464 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 465 | vec![ToolCapability::ReadOnly] |
| 466 | } |
| 467 | |
| 468 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 469 | ApprovalRequirement::Auto |
| 470 | } |
| 471 | |
| 472 | async fn execute( |
| 473 | &self, |
| 474 | _input: Value, |
| 475 | _context: &ToolContext, |
| 476 | ) -> Result<ToolResult, ToolError> { |
| 477 | Err(ToolError::execution_failed( |
| 478 | "request_user_input must be handled by the engine", |
| 479 | )) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | #[cfg(test)] |
| 484 | mod tests { |
| 485 | use super::*; |
| 486 | |
| 487 | #[test] |
| 488 | fn validates_request_shape() { |
| 489 | let request = UserInputRequest { |
| 490 | require_typed_answers: false, |
| 491 | questions: vec![UserInputQuestion { |
| 492 | header: "Pick".to_string(), |
| 493 | id: "choice".to_string(), |
| 494 | question: "Which option?".to_string(), |
| 495 | detail: None, |
| 496 | intent: None, |
| 497 | options: vec![ |
| 498 | UserInputOption { |
| 499 | label: "A".to_string(), |
| 500 | description: "Option A".to_string(), |
| 501 | }, |
| 502 | UserInputOption { |
| 503 | label: "B".to_string(), |
| 504 | description: "Option B".to_string(), |
| 505 | }, |
| 506 | ], |
| 507 | allow_free_text: false, |
| 508 | multi_select: false, |
| 509 | }], |
| 510 | }; |
| 511 | assert!(request.validate().is_ok()); |
| 512 | for count in [0, 1, 100, 1000] { |
| 513 | let menu: UserInputRequest = serde_json::from_value(json!({ |
| 514 | "require_typed_answers":true, |
| 515 | "questions":[{"id":"menu", "question":"Choose", "allow_free_text":true, |
| 516 | "options":(0..count).map(|i| json!({"label":format!("Choice {i}")})).collect::<Vec<_>>() }] |
| 517 | })).unwrap(); |
| 518 | assert!(menu.validate_transport().is_ok()); |
| 519 | assert!(menu.validate().is_err()); |
| 520 | assert!(menu.questions[0].header.is_empty()); |
| 521 | assert!( |
| 522 | menu.questions[0] |
| 523 | .options |
| 524 | .iter() |
| 525 | .all(|option| option.description.is_empty()) |
| 526 | ); |
| 527 | } |
| 528 | let mut menu: UserInputRequest = serde_json::from_value(json!({ |
| 529 | "require_typed_answers":true, |
| 530 | "questions":[{"id":"menu", "question":"Choose", "allow_free_text":true, "multi_select":true, |
| 531 | "options":[{"label":"Other"},{"label":"left, right"}]}] |
| 532 | })).unwrap(); |
| 533 | let mut response: UserInputResponse = serde_json::from_value(json!({"answers":[ |
| 534 | {"id":"menu","kind":"choice","label":"Other","value":"Other"}, |
| 535 | {"id":"menu","kind":"choice","label":"left, right","value":"left, right"}, |
| 536 | {"id":"menu","kind":"custom","label":"","value":"custom text"} |
| 537 | ]})) |
| 538 | .unwrap(); |
| 539 | assert!(menu.validate_response(&response).is_ok()); |
| 540 | let exact = serde_json::to_value(&response).unwrap(); |
| 541 | assert_eq!(exact["answers"][1]["value"], "left, right"); |
| 542 | menu.questions[0].multi_select = false; |
| 543 | assert!(menu.validate_response(&response).is_err()); |
| 544 | menu.questions[0].multi_select = true; |
| 545 | response.answers.push(response.answers[0].clone()); |
| 546 | assert!(menu.validate_response(&response).is_err()); |
| 547 | response.answers.pop(); |
| 548 | response.answers[0].kind = None; |
| 549 | assert!(menu.validate_response(&response).is_err()); |
| 550 | for answers in [ |
| 551 | json!([]), |
| 552 | json!([{"id":"unknown","kind":"skipped","label":"","value":""}]), |
| 553 | json!([{"id":"menu","kind":"choice","label":"unknown","value":"unknown"}]), |
| 554 | json!([{"id":"menu","kind":"choice","label":"Other","value":"wrong"}]), |
| 555 | json!([{"id":"menu","kind":"custom","label":"Other","value":"text"}]), |
| 556 | json!([{"id":"menu","kind":"custom","label":"","value":" "}]), |
| 557 | json!([{"id":"menu","kind":"skipped","label":"","value":""},{"id":"menu","kind":"custom","label":"","value":"text"}]), |
| 558 | ] { |
| 559 | let response = serde_json::from_value(json!({"answers":answers})).unwrap(); |
| 560 | assert!(menu.validate_response(&response).is_err()); |
| 561 | } |
| 562 | let skipped = serde_json::from_value( |
| 563 | json!({"answers":[{"id":"menu","kind":"skipped","label":"","value":""}]}), |
| 564 | ) |
| 565 | .unwrap(); |
| 566 | assert!(menu.validate_response(&skipped).is_ok()); |
| 567 | let custom = serde_json::from_value( |
| 568 | json!({"answers":[{"id":"menu","kind":"custom","label":"","value":"legacy custom"}]}), |
| 569 | ) |
| 570 | .unwrap(); |
| 571 | menu.questions[0].allow_free_text = false; |
| 572 | assert!(menu.validate_response(&custom).is_err()); |
| 573 | menu.require_typed_answers = false; |
| 574 | assert!(menu.validate_response(&custom).is_ok()); |
| 575 | let mixed = serde_json::from_value(json!({"answers":[{"id":"menu","kind":"custom","label":"","value":"legacy custom"},{"id":"menu","label":"Other","value":"Other"}]})).unwrap(); |
| 576 | assert!(menu.validate_response(&mixed).is_err()); |
| 577 | menu.require_typed_answers = true; |
| 578 | menu.questions[0].allow_free_text = true; |
| 579 | menu.questions[0].intent = Some(UserInputIntent::PlanReview { |
| 580 | approve: "Other".into(), |
| 581 | call_id: Some("display-only".into()), |
| 582 | }); |
| 583 | assert!(menu.validate_transport().is_err()); |
| 584 | menu.questions[0].detail = Some("Plan detail".into()); |
| 585 | assert!(menu.validate_transport().is_ok()); |
| 586 | menu.questions[0].options[0].label = "Different".into(); |
| 587 | assert!(menu.validate_transport().is_err()); |
| 588 | menu.questions[0].intent = None; |
| 589 | menu.questions.push(menu.questions[0].clone()); |
| 590 | assert!(menu.validate_transport().is_err()); |
| 591 | menu.questions.pop(); |
| 592 | menu.questions[0].options = vec![ |
| 593 | UserInputOption { |
| 594 | label: "duplicate".into(), |
| 595 | description: String::new() |
| 596 | }; |
| 597 | 1001 |
| 598 | ]; |
| 599 | assert!(menu.validate_transport().is_err()); |
| 600 | menu.questions[0].options.truncate(2); |
| 601 | assert!(menu.validate_transport().is_err()); |
| 602 | menu.questions[0].options.clear(); |
| 603 | menu.questions[0].allow_free_text = false; |
| 604 | assert!(menu.validate_transport().is_err()); |
| 605 | menu.questions[0].allow_free_text = true; |
| 606 | menu.questions[0].detail = Some("x".repeat(1024 * 1024)); |
| 607 | assert!(menu.validate_transport().is_err()); |
| 608 | } |
| 609 | |
| 610 | #[test] |
| 611 | fn from_value_accepts_four_options_and_flags() { |
| 612 | // Mirrors the json!-literal style used in tools/subagent/tests.rs and |
| 613 | // exercises the schema-loosening from issue #3102: 4 options (was capped |
| 614 | // at 3) plus the new allow_free_text / multi_select flags. |
| 615 | let input = json!({ |
| 616 | "questions": [{ |
| 617 | "header": "Scope", |
| 618 | "id": "scope", |
| 619 | "question": "Which surfaces should this change affect?", |
| 620 | "options": [ |
| 621 | { "label": "TUI", "description": "Visible modal flow only" }, |
| 622 | { "label": "Headless", "description": "Protocol event only" }, |
| 623 | { "label": "All surfaces", "description": "TUI and headless" }, |
| 624 | { "label": "CLI", "description": "Command-line surface" } |
| 625 | ], |
| 626 | "allow_free_text": true, |
| 627 | "multi_select": true |
| 628 | }] |
| 629 | }); |
| 630 | let request = UserInputRequest::from_value(&input).expect("4 options + flags parse"); |
| 631 | assert_eq!(request.questions.len(), 1); |
| 632 | assert_eq!(request.questions[0].options.len(), 4); |
| 633 | assert!(request.questions[0].allow_free_text); |
| 634 | assert!(request.questions[0].multi_select); |
| 635 | let mut input = input; |
| 636 | input["require_typed_answers"] = json!(true); |
| 637 | assert!( |
| 638 | !UserInputRequest::from_value(&input) |
| 639 | .unwrap() |
| 640 | .require_typed_answers |
| 641 | ); |
| 642 | } |
| 643 | |
| 644 | #[test] |
| 645 | fn from_value_defaults_flags_when_omitted() { |
| 646 | // Backwards compatibility: a legacy payload omitting the new boolean |
| 647 | // fields must still parse, defaulting both to false. |
| 648 | let input = json!({ |
| 649 | "questions": [{ |
| 650 | "header": "Pick", |
| 651 | "id": "choice", |
| 652 | "question": "Which?", |
| 653 | "options": [ |
| 654 | { "label": "A", "description": "a" }, |
| 655 | { "label": "B", "description": "b" } |
| 656 | ] |
| 657 | }] |
| 658 | }); |
| 659 | let request = UserInputRequest::from_value(&input).expect("legacy payload parses"); |
| 660 | assert!(!request.questions[0].allow_free_text); |
| 661 | assert!(!request.questions[0].multi_select); |
| 662 | } |
| 663 | |
| 664 | #[test] |
| 665 | fn rejects_five_options() { |
| 666 | let input = json!({ |
| 667 | "questions": [{ |
| 668 | "header": "Pick", |
| 669 | "id": "choice", |
| 670 | "question": "Which?", |
| 671 | "options": [ |
| 672 | { "label": "A", "description": "a" }, |
| 673 | { "label": "B", "description": "b" }, |
| 674 | { "label": "C", "description": "c" }, |
| 675 | { "label": "D", "description": "d" }, |
| 676 | { "label": "E", "description": "e" } |
| 677 | ] |
| 678 | }] |
| 679 | }); |
| 680 | let err = UserInputRequest::from_value(&input).expect_err("5 options must fail"); |
| 681 | assert!(err.to_string().contains("at most 4 options (got 5)")); |
| 682 | } |
| 683 | |
| 684 | fn yes_no_question(header: &str, id: &str) -> UserInputQuestion { |
| 685 | UserInputQuestion { |
| 686 | header: header.to_string(), |
| 687 | id: id.to_string(), |
| 688 | question: "?".to_string(), |
| 689 | detail: None, |
| 690 | intent: None, |
| 691 | options: vec![ |
| 692 | UserInputOption { |
| 693 | label: "A".to_string(), |
| 694 | description: "A".to_string(), |
| 695 | }, |
| 696 | UserInputOption { |
| 697 | label: "B".to_string(), |
| 698 | description: "B".to_string(), |
| 699 | }, |
| 700 | ], |
| 701 | allow_free_text: false, |
| 702 | multi_select: false, |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | fn questions(count: usize) -> UserInputRequest { |
| 707 | UserInputRequest { |
| 708 | require_typed_answers: false, |
| 709 | questions: (1..=count) |
| 710 | .map(|i| yes_no_question(&format!("Q{i}"), &format!("q{i}"))) |
| 711 | .collect(), |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | #[test] |
| 716 | fn default_limits_are_six_questions_and_four_options() { |
| 717 | let limits = UserInputLimits::default(); |
| 718 | assert_eq!(limits.max_questions, 6); |
| 719 | assert_eq!(limits.max_options, 4); |
| 720 | // An empty `[tools]` table resolves to the same ceilings. |
| 721 | assert_eq!(UserInputLimits::from_config_values(None, None), limits); |
| 722 | let tool = RequestUserInputTool::default(); |
| 723 | let description = tool.description(); |
| 724 | assert!(description.contains("Ask the user 1-6 short multiple-choice questions")); |
| 725 | assert!(description.contains("Blocks until answered.")); |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn accepts_six_questions_by_default() { |
| 730 | assert!(questions(6).validate().is_ok()); |
| 731 | } |
| 732 | |
| 733 | #[test] |
| 734 | fn rejects_seven_questions_and_names_the_config_key() { |
| 735 | let err = questions(7) |
| 736 | .validate() |
| 737 | .expect_err("7 questions exceeds the default ceiling of 6"); |
| 738 | let msg = err.to_string(); |
| 739 | assert!(msg.contains("1 to 6 items"), "{msg}"); |
| 740 | assert!(msg.contains("got 7"), "{msg}"); |
| 741 | assert!(msg.contains("[tools] user_input_max_questions"), "{msg}"); |
| 742 | assert!(msg.contains("config.toml"), "{msg}"); |
| 743 | } |
| 744 | |
| 745 | #[test] |
| 746 | fn rejected_option_count_names_the_config_key() { |
| 747 | let input = json!({ |
| 748 | "questions": [{ |
| 749 | "header": "Pick", |
| 750 | "id": "choice", |
| 751 | "question": "Which?", |
| 752 | "options": [ |
| 753 | { "label": "A", "description": "a" }, |
| 754 | { "label": "B", "description": "b" }, |
| 755 | { "label": "C", "description": "c" }, |
| 756 | { "label": "D", "description": "d" }, |
| 757 | { "label": "E", "description": "e" } |
| 758 | ] |
| 759 | }] |
| 760 | }); |
| 761 | let msg = UserInputRequest::from_value(&input) |
| 762 | .expect_err("5 options must fail") |
| 763 | .to_string(); |
| 764 | assert!(msg.contains("[tools] user_input_max_options"), "{msg}"); |
| 765 | } |
| 766 | |
| 767 | #[test] |
| 768 | fn configured_limits_widen_and_narrow_the_validator() { |
| 769 | let wide = UserInputLimits::from_config_values(Some(9), Some(6)); |
| 770 | assert!(questions(9).validate_with_limits(wide).is_ok()); |
| 771 | |
| 772 | let narrow = UserInputLimits::from_config_values(Some(2), None); |
| 773 | let msg = questions(3) |
| 774 | .validate_with_limits(narrow) |
| 775 | .expect_err("3 questions exceeds a configured ceiling of 2") |
| 776 | .to_string(); |
| 777 | assert!(msg.contains("1 to 2 items"), "{msg}"); |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn out_of_range_config_values_clamp() { |
| 782 | // Below the floor and far above the ceiling both clamp instead of |
| 783 | // failing the config load. |
| 784 | let low = UserInputLimits::from_config_values(Some(0), Some(0)); |
| 785 | assert_eq!(low.max_questions, MIN_CONFIGURABLE_QUESTIONS); |
| 786 | assert_eq!(low.max_options, MIN_CONFIGURABLE_OPTIONS); |
| 787 | |
| 788 | let high = UserInputLimits::from_config_values(Some(50), Some(50)); |
| 789 | assert_eq!(high.max_questions, MAX_CONFIGURABLE_QUESTIONS); |
| 790 | assert_eq!(high.max_options, MAX_CONFIGURABLE_OPTIONS); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn schema_and_description_reflect_configured_limits() { |
| 795 | let tool = RequestUserInputTool::new(UserInputLimits::from_config_values(Some(8), Some(5))); |
| 796 | let description = tool.description(); |
| 797 | assert!(description.contains("Ask the user 1-8 short multiple-choice questions")); |
| 798 | assert!(description.contains("Blocks until answered.")); |
| 799 | let schema = tool.input_schema(); |
| 800 | let questions = &schema["properties"]["questions"]; |
| 801 | assert_eq!(questions["minItems"], json!(1)); |
| 802 | assert_eq!(questions["maxItems"], json!(8)); |
| 803 | let options = &questions["items"]["properties"]["options"]; |
| 804 | assert_eq!(options["minItems"], json!(2)); |
| 805 | assert_eq!(options["maxItems"], json!(5)); |
| 806 | |
| 807 | // Defaults land on the documented 6 / 4 pair. |
| 808 | let default_schema = RequestUserInputTool::default().input_schema(); |
| 809 | assert_eq!( |
| 810 | default_schema["properties"]["questions"]["maxItems"], |
| 811 | json!(6) |
| 812 | ); |
| 813 | assert_eq!( |
| 814 | default_schema["properties"]["questions"]["items"]["properties"]["options"]["maxItems"], |
| 815 | json!(4) |
| 816 | ); |
| 817 | } |
| 818 | |
| 819 | #[test] |
| 820 | fn rejects_too_many_questions() { |
| 821 | // Seven is one past the default ceiling; four now parses (#5949). |
| 822 | assert!(questions(4).validate().is_ok()); |
| 823 | assert!(questions(7).validate().is_err()); |
| 824 | } |
| 825 | } |
| 826 |