Skip to main content

aither_sandbox/
command.rs

1//! Tool-to-command conversion using JSON schema.
2//!
3//! Wraps any `Tool` as an IPC command callable from the sandbox.
4//! Uses the existing JSON schema to generate CLI parsing - no clap needed.
5//!
6//! # Architecture
7//!
8//! Tools are registered with [`ToolRegistryBuilder`] and stored in a
9//! [`ToolRegistry`]. [`ToolCallCommand`] implements `IpcCommand` and
10//! dispatches to the appropriate handler based on the tool name.
11//!
12//! # Example
13//!
14//! ```rust,ignore
15//! use aither_sandbox::command::{ToolRegistryBuilder, register_tool_command};
16//! use aither_sandbox::builtin::builtin_router;
17//!
18//! // Configure tools
19//! let mut registry = ToolRegistryBuilder::new();
20//! registry.configure_tool(websearch_tool);
21//! registry.configure_tool(webfetch_tool);
22//! let registry = std::sync::Arc::new(registry.build("./outputs"));
23//!
24//! // Register tool commands with router
25//! let router = builtin_router();
26//! let router = register_tool_command(router, registry.clone(), "websearch");
27//! let router = register_tool_command(router, registry.clone(), "webfetch");
28//! ```
29
30use std::borrow::Cow;
31use std::collections::{HashMap, HashSet};
32use std::future::Future;
33use std::path::{Path, PathBuf};
34use std::pin::Pin;
35use std::sync::Arc;
36
37use aither_core::llm::{IntoToolResult, Tool, ToolResult};
38use askama::Template;
39use base64::Engine as _;
40use heel::IpcCommand;
41use schemars::JsonSchema;
42use serde::de::DeserializeOwned;
43use serde::{Deserialize, Serialize};
44use serde_json::Value;
45
46// ============================================================================
47// Tool Registry
48// ============================================================================
49
50/// Payload exchanged between IPC command handlers and terminal command wrappers.
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
52#[serde(tag = "kind", rename_all = "snake_case")]
53pub enum CommandPayload {
54    /// UTF-8 text output.
55    Text {
56        /// Text content.
57        content: String,
58    },
59    /// Structured JSON output.
60    Json {
61        /// JSON value.
62        value: Value,
63    },
64    /// Binary output encoded as base64 with a MIME type.
65    Binary {
66        /// MIME type of the binary payload.
67        mime: String,
68        /// Base64-encoded bytes.
69        data_base64: String,
70    },
71}
72
73#[derive(Template)]
74#[template(path = "command_output_saved.txt", escape = "none")]
75struct CommandOutputSavedTemplate<'a> {
76    preview: &'a str,
77    filename: &'a str,
78    line_count: usize,
79    byte_count: usize,
80}
81
82#[derive(Template)]
83#[template(path = "tool_usage_error.txt", escape = "none")]
84struct ToolUsageErrorTemplate<'a> {
85    message: &'a str,
86    tool_name: &'a str,
87}
88
89#[derive(Template)]
90#[template(path = "ipc_gateway_help.txt", escape = "none")]
91struct IpcGatewayHelpTemplate<'a> {
92    tool_names: &'a str,
93}
94
95fn prefix_error(prefix: &str, error: &impl std::fmt::Display) -> String {
96    let error_text = error.to_string();
97    let mut message = String::with_capacity(prefix.len() + error_text.len());
98    message.push_str(prefix);
99    message.push_str(error_text.as_str());
100    message
101}
102
103fn tool_usage_error(message: &str, tool_name: &str) -> String {
104    ToolUsageErrorTemplate { message, tool_name }
105        .render()
106        .expect("tool usage error template must render")
107}
108
109fn output_saved_text(
110    rendered: &str,
111    filename: &str,
112    line_count: usize,
113    byte_count: usize,
114) -> String {
115    let preview = crate::output::head_preview(rendered, usize::MAX, INLINE_OUTPUT_LIMIT);
116    CommandOutputSavedTemplate {
117        preview: preview.trim_end_matches('\n'),
118        filename,
119        line_count,
120        byte_count,
121    }
122    .render()
123    .expect("command output saved template must render")
124}
125
126fn unknown_command_text(tool_name: &str) -> String {
127    let mut message = String::with_capacity(tool_name.len() + 47);
128    message.push_str("unknown command '");
129    message.push_str(tool_name);
130    message.push_str("'. Run 'help' to see available commands.");
131    message
132}
133
134fn no_help_available_text(tool_name: &str) -> String {
135    let mut message = String::with_capacity(tool_name.len() + 23);
136    message.push_str("No help available for '");
137    message.push_str(tool_name);
138    message.push('\'');
139    message
140}
141
142fn push_help_line(help: &mut String, line: &str) {
143    help.push_str(line);
144    help.push('\n');
145}
146
147fn render_positional_usage(name: &str) -> String {
148    let kebab = name.replace('_', "-");
149    let mut output = String::with_capacity(kebab.len() + 2);
150    output.push('<');
151    output.push_str(kebab.as_str());
152    output.push('>');
153    output
154}
155
156fn render_repeatable_usage(name: &str) -> String {
157    let kebab = name.replace('_', "-");
158    let mut output = String::with_capacity(kebab.len() + 12);
159    output.push_str("--");
160    output.push_str(kebab.as_str());
161    output.push_str(" <value>...");
162    output
163}
164
165fn render_flag_prefix(flag: &str, short: Option<char>) -> String {
166    let mut output = String::with_capacity(flag.len() + 8);
167    output.push_str("  ");
168    if let Some(short) = short {
169        output.push('-');
170        output.push(short);
171        output.push_str(", ");
172    }
173    output.push_str("--");
174    output.push_str(flag);
175    output
176}
177
178impl CommandPayload {
179    fn render_for_cli(&self) -> Result<String, String> {
180        match self {
181            Self::Text { content } => Ok(content.clone()),
182            Self::Json { value } => serde_json::to_string_pretty(value)
183                .map_err(|error| prefix_error("failed to encode JSON output: ", &error)),
184            Self::Binary { mime, data_base64 } => {
185                let mut rendered = String::new();
186                rendered.push_str("[binary payload: ");
187                rendered.push_str(mime);
188                rendered.push_str(", ");
189                rendered.push_str(data_base64.len().to_string().as_str());
190                rendered.push_str(" base64 chars]");
191                Ok(rendered)
192            }
193        }
194    }
195}
196
197/// Command result envelope returned to IPC callers.
198#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
199#[serde(rename_all = "camelCase")]
200pub struct CommandEnvelope {
201    /// Whether command execution succeeded.
202    pub ok: bool,
203    /// Optional successful command payload.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub payload: Option<CommandPayload>,
206    /// Optional command error text.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub error: Option<String>,
209}
210
211impl CommandEnvelope {
212    const fn success(payload: CommandPayload) -> Self {
213        Self {
214            ok: true,
215            payload: Some(payload),
216            error: None,
217        }
218    }
219
220    const fn success_empty() -> Self {
221        Self {
222            ok: true,
223            payload: None,
224            error: None,
225        }
226    }
227
228    fn failure(message: impl Into<String>) -> Self {
229        Self {
230            ok: false,
231            payload: None,
232            error: Some(message.into()),
233        }
234    }
235}
236
237/// Type-erased tool handler function.
238type ToolHandlerFn = Box<
239    dyn Fn(
240            Vec<String>,
241        ) -> Pin<Box<dyn Future<Output = Result<Option<CommandPayload>, String>> + Send>>
242        + Send
243        + Sync,
244>;
245
246/// Tool entry in the registry.
247struct ToolEntry {
248    handler: ToolHandlerFn,
249    help: String,
250    positional_args: Vec<String>,
251    stdin_arg: Option<String>,
252}
253
254impl std::fmt::Debug for ToolEntry {
255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256        f.debug_struct("ToolEntry")
257            .field("help", &self.help)
258            .field("positional_args", &self.positional_args)
259            .field("stdin_arg", &self.stdin_arg)
260            .finish_non_exhaustive()
261    }
262}
263
264use crate::output::{INLINE_OUTPUT_LIMIT, generate_word_filename};
265
266/// Handles large outputs by saving to file in the sandbox output directory.
267///
268/// Returns the output as-is if small enough, or saves to file and returns
269/// a reference message if the output exceeds the limit.
270async fn handle_large_output(output: Option<CommandPayload>, output_dir: &Path) -> CommandEnvelope {
271    let Some(output) = output else {
272        return CommandEnvelope::success_empty();
273    };
274
275    let rendered = match output.render_for_cli() {
276        Ok(rendered) => rendered,
277        Err(error) => return CommandEnvelope::failure(error),
278    };
279
280    if rendered.is_empty() {
281        return CommandEnvelope::success_empty();
282    }
283
284    if rendered.len() <= INLINE_OUTPUT_LIMIT {
285        return CommandEnvelope::success(output);
286    }
287
288    // Generate four-random-words filename (consistent with rest of codebase)
289    let mut filename = generate_word_filename();
290    filename.push_str(".txt");
291    let filepath = output_dir.join(&filename);
292
293    let line_count = rendered.lines().count();
294
295    if let Err(error) = async_fs::write(&filepath, &rendered).await {
296        let filepath_text = filepath.display().to_string();
297        let error_text = error.to_string();
298        let mut message = String::with_capacity(filepath_text.len() + error_text.len() + 25);
299        message.push_str("failed to write output to ");
300        message.push_str(filepath_text.as_str());
301        message.push_str(": ");
302        message.push_str(error_text.as_str());
303        return CommandEnvelope::failure(message);
304    }
305
306    CommandEnvelope::success(CommandPayload::Text {
307        content: output_saved_text(&rendered, filename.as_str(), line_count, rendered.len()),
308    })
309}
310
311fn tool_output_to_payload(output: impl IntoToolResult) -> Result<Option<CommandPayload>, String> {
312    match output
313        .into_tool_result()
314        .map_err(|error| prefix_error("failed to convert tool result: ", &error))?
315    {
316        ToolResult::Done => Ok(None),
317        ToolResult::Text { text } | ToolResult::Tsv { text } => {
318            Ok(Some(CommandPayload::Text { content: text }))
319        }
320        ToolResult::Json { value } => Ok(Some(CommandPayload::Json { value })),
321        ToolResult::Binary { mime, content } => Ok(Some(CommandPayload::Binary {
322            mime,
323            data_base64: base64::engine::general_purpose::STANDARD.encode(content),
324        })),
325        ToolResult::Error { message } => Err(message),
326    }
327}
328
329// ============================================================================
330// Terminal Tool Factory (for creating child terminal tools for subagents)
331// ============================================================================
332
333use aither_core::llm::tool::ToolDefinition;
334
335/// A type-erased handler function for terminal tools.
336pub type DynToolHandler =
337    Arc<dyn Fn(&str) -> Pin<Box<dyn Future<Output = ToolResult> + Send>> + Send + Sync>;
338
339/// One type-erased tool in a terminal capability bundle.
340pub struct DynTerminalToolEntry {
341    /// Tool definition exposed to the model.
342    pub definition: ToolDefinition,
343    /// Handler that takes JSON arguments and returns a result.
344    pub handler: DynToolHandler,
345}
346
347impl std::fmt::Debug for DynTerminalToolEntry {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        f.debug_struct("DynTerminalToolEntry")
350            .field("definition", &self.definition)
351            .finish_non_exhaustive()
352    }
353}
354
355/// A type-erased terminal capability bundle for child agents.
356pub struct DynTerminalTool {
357    pub(crate) entries: Vec<DynTerminalToolEntry>,
358    pub(crate) background_receiver: crate::terminal::BackgroundTaskReceiver,
359    pub(crate) permission_receiver: crate::terminal::PermissionEventReceiver,
360    pub(crate) job_registry: crate::job_registry::JobRegistry,
361    pub(crate) working_dir: PathBuf,
362}
363
364impl DynTerminalTool {
365    /// Returns the receiver for background terminal completions.
366    #[must_use]
367    pub fn background_receiver(&self) -> crate::terminal::BackgroundTaskReceiver {
368        self.background_receiver.clone()
369    }
370
371    /// Returns the receiver for terminal permission lifecycle events.
372    #[must_use]
373    pub fn permission_receiver(&self) -> crate::terminal::PermissionEventReceiver {
374        self.permission_receiver.clone()
375    }
376
377    /// Returns the child terminal job registry.
378    #[must_use]
379    pub fn job_registry(&self) -> crate::job_registry::JobRegistry {
380        self.job_registry.clone()
381    }
382
383    /// Returns the shared terminal working directory.
384    #[must_use]
385    pub const fn working_dir(&self) -> &PathBuf {
386        &self.working_dir
387    }
388
389    /// Consumes the bundle and returns every native terminal tool entry.
390    #[must_use]
391    pub fn into_entries(self) -> Vec<DynTerminalToolEntry> {
392        self.entries
393    }
394}
395
396impl std::fmt::Debug for DynTerminalTool {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        f.debug_struct("DynTerminalTool")
399            .field("entries", &self.entries)
400            .field("working_dir", &self.working_dir)
401            .finish_non_exhaustive()
402    }
403}
404
405/// Builder for tool registries.
406#[derive(Debug, Default)]
407pub struct ToolRegistryBuilder {
408    entries: HashMap<String, ToolEntry>,
409}
410
411impl ToolRegistryBuilder {
412    /// Creates an empty registry builder.
413    #[must_use]
414    pub fn new() -> Self {
415        Self {
416            entries: HashMap::new(),
417        }
418    }
419
420    /// Configures a tool to be callable from the sandbox.
421    ///
422    /// The positional arguments are automatically detected from the schema -
423    /// all required fields become positional args in order.
424    /// For example, if a tool has `query: String` as its first required field,
425    /// then `websearch "rust"` → `websearch --query "rust"`.
426    ///
427    /// # Panics
428    /// Panics if the tool argument schema cannot be serialized.
429    pub fn configure_tool<T>(&mut self, tool: T)
430    where
431        T: Tool + Send + Sync + 'static,
432        T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
433    {
434        let schema = serde_json::to_value(schemars::schema_for!(T::Arguments))
435            .expect("failed to serialize tool schema");
436
437        // Auto-detect positional args from schema: all required fields
438        let positional_args = detect_positional_args(&schema);
439        // Auto-detect stdin_arg from schema: optional "input" field
440        let stdin_arg = detect_stdin_arg(&schema);
441
442        let tool = Arc::new(tool);
443        let tool_name = tool.name().to_string();
444        let help_text = schema_to_help(&schema);
445
446        let name_for_errors = tool_name.clone();
447        let handler: ToolHandlerFn = Box::new(move |args: Vec<String>| {
448            let tool = tool.clone();
449            let schema = schema.clone();
450            let name = name_for_errors.clone();
451            Box::pin(async move {
452                tracing::debug!(tool = %name, ?args, "configure_tool handler: raw CLI args");
453                let json_args = match cli_to_json(&schema, &args) {
454                    Ok(v) => v,
455                    Err(e) => {
456                        let message = e.to_string();
457                        return Err(tool_usage_error(message.as_str(), name.as_str()));
458                    }
459                };
460                tracing::debug!(tool = %name, json = %json_args, "configure_tool handler: parsed JSON");
461                let parsed = match serde_json::from_value(json_args) {
462                    Ok(v) => v,
463                    Err(e) => {
464                        let message = prefix_error("invalid arguments: ", &e);
465                        return Err(tool_usage_error(message.as_str(), name.as_str()));
466                    }
467                };
468                let output = tool.call(parsed).await.map_err(|error| error.to_string())?;
469                tool_output_to_payload(output)
470            })
471        });
472
473        self.entries.insert(
474            tool_name,
475            ToolEntry {
476                handler,
477                help: help_text,
478                positional_args,
479                stdin_arg,
480            },
481        );
482    }
483
484    /// Configures a schema-defined handler to be callable from the sandbox.
485    ///
486    /// This is the dynamic counterpart to [`Self::configure_tool`]. The CLI
487    /// wrapper is derived entirely from the provided [`ToolDefinition`]'s JSON
488    /// schema, so external tools such as MCP definitions get the same
489    /// positional arguments, `--help`, and usage validation behavior as native
490    /// `Tool` implementations.
491    pub fn configure_definition_handler<F>(&mut self, definition: &ToolDefinition, handler: F)
492    where
493        F: Fn(
494                Value,
495            )
496                -> Pin<Box<dyn Future<Output = Result<Option<CommandPayload>, String>> + Send>>
497            + Send
498            + Sync
499            + 'static,
500    {
501        let name = definition.name().to_string();
502        let description = definition.description().to_string();
503        let schema = definition.arguments_openai_schema();
504        let positional_args = detect_positional_args(&schema);
505        let stdin_arg = detect_stdin_arg(&schema);
506        let help_text = if description.is_empty() {
507            schema_to_help(&schema)
508        } else {
509            let mut help = String::with_capacity(description.len() + 2);
510            help.push_str(description.as_str());
511            help.push_str("\n\n");
512            help.push_str(schema_to_help(&schema).as_str());
513            help
514        };
515
516        let schema_for_handler = schema;
517        let name_for_handler = name.clone();
518        let handler = Arc::new(handler);
519        let raw_handler: ToolHandlerFn = Box::new(move |args: Vec<String>| {
520            let schema = schema_for_handler.clone();
521            let name = name_for_handler.clone();
522            let handler = handler.clone();
523            Box::pin(async move {
524                let json_args = match cli_to_json(&schema, &args) {
525                    Ok(value) => value,
526                    Err(error) => {
527                        let message = error.to_string();
528                        return Err(tool_usage_error(message.as_str(), name.as_str()));
529                    }
530                };
531                handler(json_args).await
532            })
533        });
534
535        self.entries.insert(
536            name,
537            ToolEntry {
538                handler: raw_handler,
539                help: help_text,
540                positional_args,
541                stdin_arg,
542            },
543        );
544    }
545
546    /// Registers a raw handler function as an IPC command.
547    ///
548    /// This is useful for dynamic tools like MCP tools that are discovered at runtime.
549    pub fn configure_raw_handler<F>(
550        &mut self,
551        name: impl Into<String>,
552        help: impl Into<String>,
553        positional_args: Vec<String>,
554        handler: F,
555    ) where
556        F: Fn(
557                Vec<String>,
558            )
559                -> Pin<Box<dyn Future<Output = Result<Option<CommandPayload>, String>> + Send>>
560            + Send
561            + Sync
562            + 'static,
563    {
564        self.entries.insert(
565            name.into(),
566            ToolEntry {
567                handler: Box::new(handler),
568                help: help.into(),
569                positional_args,
570                stdin_arg: None,
571            },
572        );
573    }
574
575    /// Builds an immutable registry with a concrete output directory.
576    #[must_use]
577    pub fn build(self, output_dir: impl Into<PathBuf>) -> ToolRegistry {
578        ToolRegistry {
579            entries: self.entries,
580            output_dir: output_dir.into(),
581        }
582    }
583}
584
585/// Immutable registry of tool handlers.
586#[derive(Debug)]
587pub struct ToolRegistry {
588    entries: HashMap<String, ToolEntry>,
589    output_dir: PathBuf,
590}
591
592/// Detects positional arguments from a JSON schema.
593///
594/// Returns required field names that are suitable for positional argument
595/// conversion in wrapper scripts. Array-typed fields are excluded because
596/// they need repeated `--flag value` syntax (e.g. `--options A --options B`).
597fn detect_positional_args(schema: &Value) -> Vec<String> {
598    let properties = schema.get("properties").and_then(Value::as_object);
599
600    let required: Vec<String> = schema
601        .get("required")
602        .and_then(|r| r.as_array())
603        .map(|arr| {
604            arr.iter()
605                .filter_map(|v| v.as_str().map(String::from))
606                .collect()
607        })
608        .unwrap_or_default();
609
610    required
611        .into_iter()
612        .filter(|name| {
613            // Exclude array-typed fields -- they require repeated --flag syntax
614            if let Some(props) = properties
615                && let Some(prop_schema) = props.get(name)
616            {
617                return get_instance_type(prop_schema, prop_schema) != Some("array");
618            }
619            true
620        })
621        .collect()
622}
623
624/// Detects the stdin argument from a JSON schema.
625///
626/// Returns "input" if the schema has an "input" property that is not required.
627/// This allows stdin piping: `cat file | command "prompt"` passes stdin as --input.
628fn detect_stdin_arg(schema: &Value) -> Option<String> {
629    // Check if "input" property exists
630    let properties = schema.get("properties")?.as_object()?;
631    if !properties.contains_key("input") {
632        return None;
633    }
634
635    // Check that "input" is NOT required (has a default)
636    let required = schema
637        .get("required")
638        .and_then(|r| r.as_array())
639        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>())
640        .unwrap_or_default();
641
642    if required.contains(&"input") {
643        return None;
644    }
645
646    Some("input".to_string())
647}
648
649impl ToolRegistry {
650    /// Queries a tool handler by name.
651    ///
652    /// Large outputs (> 4000 chars) are automatically saved to file.
653    pub async fn query_tool_handler(&self, tool_name: &str, args: &[String]) -> CommandEnvelope {
654        let entry = self.entries.get(tool_name);
655        match entry {
656            Some(entry) => match (entry.handler)(args.to_vec()).await {
657                Ok(output) => handle_large_output(output, &self.output_dir).await,
658                Err(error) => CommandEnvelope::failure(error),
659            },
660            None => CommandEnvelope::failure(unknown_command_text(tool_name)),
661        }
662    }
663
664    /// Returns whether a tool is registered.
665    #[must_use]
666    pub fn is_tool_configured(&self, tool_name: &str) -> bool {
667        self.entries.contains_key(tool_name)
668    }
669
670    /// Returns the help text for a tool.
671    #[must_use]
672    pub fn tool_help(&self, tool_name: &str) -> Option<String> {
673        self.entries.get(tool_name).map(|e| e.help.clone())
674    }
675
676    /// Returns the positional arguments for a tool.
677    #[must_use]
678    pub fn tool_positional_args(&self, tool_name: &str) -> Vec<String> {
679        self.entries
680            .get(tool_name)
681            .map(|e| e.positional_args.clone())
682            .unwrap_or_default()
683    }
684
685    /// Returns the stdin argument for a tool.
686    #[must_use]
687    pub fn tool_stdin_arg(&self, tool_name: &str) -> Option<String> {
688        self.entries
689            .get(tool_name)
690            .and_then(|e| e.stdin_arg.clone())
691    }
692
693    /// Returns list of registered tool names.
694    #[must_use]
695    pub fn registered_tool_names(&self) -> Vec<String> {
696        self.entries.keys().cloned().collect()
697    }
698}
699
700// ============================================================================
701// IPC Command for Tools
702// ============================================================================
703
704/// IPC command for invoking tools from the sandbox.
705///
706/// The `tool_name` comes from the IPC method name, and args are flattened
707/// from the key-value pairs sent by `heel ipc`.
708#[derive(Debug, Clone)]
709pub struct ToolCallCommand {
710    /// Shared tool registry.
711    pub registry: Arc<ToolRegistry>,
712    /// Name of the tool this instance invokes.
713    ///
714    /// One instance is registered per tool, so the name is fixed at
715    /// construction rather than set per request.
716    pub tool_name: String,
717}
718
719impl ToolCallCommand {
720    /// Creates a new tool call command.
721    #[must_use]
722    pub fn new(tool_name: impl Into<String>, registry: Arc<ToolRegistry>) -> Self {
723        Self {
724            registry,
725            tool_name: tool_name.into(),
726        }
727    }
728}
729
730pub fn flatten_args_to_cli(args: &std::collections::HashMap<String, Value>) -> Vec<String> {
731    if let Some(Value::Array(arr)) = args.get("args") {
732        return arr
733            .iter()
734            .filter_map(|v| match v {
735                Value::String(s) => Some(s.clone()),
736                Value::Number(n) => Some(n.to_string()),
737                Value::Bool(b) => Some(b.to_string()),
738                _ => None,
739            })
740            .collect();
741    }
742
743    let mut cli_args = Vec::new();
744    let mut keys = args.keys().map(String::as_str).collect::<Vec<_>>();
745    keys.sort_unstable();
746    for key in keys {
747        let value = args
748            .get(key)
749            .expect("flatten_args_to_cli keys must resolve back into the map");
750        flatten_named_arg_to_cli(&mut cli_args, key, value);
751    }
752    cli_args
753}
754
755fn push_long_option(cli_args: &mut Vec<String>, key: &str) {
756    let mut option = String::with_capacity(key.len() + 2);
757    option.push_str("--");
758    option.push_str(key);
759    cli_args.push(option);
760}
761
762fn flatten_named_arg_to_cli(cli_args: &mut Vec<String>, key: &str, value: &Value) {
763    match value {
764        Value::Bool(true) => push_long_option(cli_args, key),
765        Value::Bool(false) => {}
766        Value::String(text) => {
767            push_long_option(cli_args, key);
768            cli_args.push(text.clone());
769        }
770        Value::Number(number) => {
771            push_long_option(cli_args, key);
772            cli_args.push(number.to_string());
773        }
774        Value::Array(items) => {
775            for item in items {
776                push_long_option(cli_args, key);
777                if let Some(text) = item.as_str() {
778                    cli_args.push(text.to_string());
779                } else {
780                    cli_args.push(item.to_string());
781                }
782            }
783        }
784        _ => {
785            push_long_option(cli_args, key);
786            cli_args.push(value.to_string());
787        }
788    }
789}
790
791impl IpcCommand for ToolCallCommand {
792    type Args = std::collections::HashMap<String, Value>;
793    type Response = CommandEnvelope;
794
795    fn name(&self) -> Cow<'static, str> {
796        Cow::Owned(self.tool_name.clone())
797    }
798
799    fn positional_args(&self) -> Cow<'static, [Cow<'static, str>]> {
800        let args = self.registry.tool_positional_args(&self.tool_name);
801        if args.is_empty() {
802            Cow::Borrowed(&[])
803        } else {
804            Cow::Owned(args.into_iter().map(Cow::Owned).collect())
805        }
806    }
807
808    fn stdin_arg(&self) -> Option<Cow<'static, str>> {
809        self.registry
810            .tool_stdin_arg(&self.tool_name)
811            .map(Cow::Owned)
812    }
813
814    async fn handle(&self, args: Self::Args) -> CommandEnvelope {
815        let cli_args = flatten_args_to_cli(&args);
816        tracing::info!(tool = %self.tool_name, args = ?cli_args, "ToolCallCommand::handle invoked");
817
818        // Handle help flags
819        if has_help_flag(&cli_args) {
820            let help = self
821                .registry
822                .tool_help(&self.tool_name)
823                .unwrap_or_else(|| no_help_available_text(self.tool_name.as_str()));
824            tracing::info!(tool = %self.tool_name, "Returning help text");
825            return CommandEnvelope::success(CommandPayload::Text { content: help });
826        }
827
828        tracing::info!(tool = %self.tool_name, "Calling registry.query_tool_handler");
829        self.registry
830            .query_tool_handler(&self.tool_name, &cli_args)
831            .await
832    }
833}
834
835/// Registers a tool command with the IPC router.
836///
837/// The tool must have been previously configured in the registry.
838///
839/// # Example
840///
841/// ```rust,ignore
842/// use aither_sandbox::command::register_tool_command;
843/// use heel::IpcRouter;
844///
845/// let router = IpcRouter::new();
846/// let registry = std::sync::Arc::new(ToolRegistryBuilder::new().build("./outputs"));
847/// let router = register_tool_command(router, registry, "websearch");
848/// ```
849#[must_use]
850pub fn register_tool_command(
851    router: heel::IpcRouter,
852    registry: Arc<ToolRegistry>,
853    tool_name: &str,
854) -> heel::IpcRouter {
855    router.register(ToolCallCommand::new(tool_name, registry))
856}
857
858#[derive(Debug, Clone)]
859pub struct IpcGatewayCommand {
860    pub registry: Arc<ToolRegistry>,
861}
862
863impl IpcGatewayCommand {
864    #[must_use]
865    pub const fn new(registry: Arc<ToolRegistry>) -> Self {
866        Self { registry }
867    }
868}
869
870impl IpcCommand for IpcGatewayCommand {
871    type Args = std::collections::HashMap<String, Value>;
872    type Response = CommandEnvelope;
873
874    fn name(&self) -> Cow<'static, str> {
875        Cow::Borrowed("ipc")
876    }
877
878    async fn handle(&self, args: Self::Args) -> CommandEnvelope {
879        let cli_args = flatten_args_to_cli(&args);
880        if cli_args.is_empty() {
881            return CommandEnvelope::failure("usage: ipc <tool> [args ...]");
882        }
883
884        if has_help_flag(&cli_args) && cli_args.len() == 1 {
885            let mut names = self.registry.registered_tool_names();
886            names.sort();
887            let joined_names = names.join(", ");
888            return CommandEnvelope::success(CommandPayload::Text {
889                content: IpcGatewayHelpTemplate {
890                    tool_names: joined_names.as_str(),
891                }
892                .render()
893                .expect("ipc gateway help template must render"),
894            });
895        }
896
897        let tool_name = &cli_args[0];
898        let tool_args = cli_args[1..].to_vec();
899        self.registry
900            .query_tool_handler(tool_name, &tool_args)
901            .await
902    }
903}
904
905/// Registers the generic `ipc` gateway command that dispatches to any tool by name.
906#[must_use]
907pub fn register_ipc_gateway_command(
908    router: heel::IpcRouter,
909    registry: Arc<ToolRegistry>,
910) -> heel::IpcRouter {
911    router.register(IpcGatewayCommand::new(registry))
912}
913
914// ============================================================================
915// ToolCommand wrapper (for direct use without IPC)
916// ============================================================================
917
918/// Wraps a Tool as an IPC command using schema-driven CLI parsing.
919pub struct ToolCommand<T: Tool> {
920    tool: T,
921    schema: Value,
922}
923
924impl<T: Tool + std::fmt::Debug> std::fmt::Debug for ToolCommand<T> {
925    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
926        f.debug_struct("ToolCommand")
927            .field("tool", &self.tool)
928            .finish_non_exhaustive()
929    }
930}
931
932impl<T: Tool> ToolCommand<T>
933where
934    T::Arguments: DeserializeOwned + JsonSchema,
935{
936    /// Creates a new command wrapper for the given tool.
937    ///
938    /// # Panics
939    /// Panics if the tool argument schema cannot be serialized.
940    pub fn new(tool: T) -> Self {
941        let schema = schemars::schema_for!(T::Arguments);
942        let schema = serde_json::to_value(schema).expect("failed to serialize tool schema");
943        Self { tool, schema }
944    }
945
946    /// Returns the tool name.
947    pub fn name(&self) -> Cow<'static, str> {
948        self.tool.name()
949    }
950
951    /// Generates help text from the JSON schema.
952    #[must_use]
953    pub fn help(&self) -> String {
954        schema_to_help(&self.schema)
955    }
956
957    /// Parses CLI arguments and executes the tool.
958    ///
959    /// # Errors
960    ///
961    /// Returns an error if argument parsing fails or tool execution fails.
962    pub async fn execute(&self, args: &[String]) -> anyhow::Result<String> {
963        let json_args = cli_to_json(&self.schema, args)?;
964        let parsed: T::Arguments = serde_json::from_value(json_args)?;
965        let output = self.tool.call(parsed).await?;
966        let payload = tool_output_to_payload(output).map_err(anyhow::Error::msg)?;
967        payload.map_or_else(
968            || Ok(String::new()),
969            |payload| payload.render_for_cli().map_err(anyhow::Error::msg),
970        )
971    }
972}
973
974/// IPC command wrapper that holds a Tool directly (no global state).
975///
976/// Use this with `router.register()` to add tools to the IPC router
977/// without relying on the global tool registry.
978pub struct IpcToolCommand<T: Tool> {
979    tool: Arc<T>,
980    schema: Value,
981    name: String,
982    positional_args: Vec<String>,
983    stdin_arg: Option<String>,
984    help: String,
985}
986
987impl<T: Tool + std::fmt::Debug> std::fmt::Debug for IpcToolCommand<T> {
988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989        f.debug_struct("IpcToolCommand")
990            .field("name", &self.name)
991            .field("tool", &self.tool)
992            .finish_non_exhaustive()
993    }
994}
995
996impl<T: Tool + Clone> Clone for IpcToolCommand<T> {
997    fn clone(&self) -> Self {
998        Self {
999            tool: self.tool.clone(),
1000            schema: self.schema.clone(),
1001            name: self.name.clone(),
1002            positional_args: self.positional_args.clone(),
1003            stdin_arg: self.stdin_arg.clone(),
1004            help: self.help.clone(),
1005        }
1006    }
1007}
1008
1009impl<T> IpcToolCommand<T>
1010where
1011    T: Tool + Send + Sync + 'static,
1012    T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
1013{
1014    /// Creates a new IPC command wrapper for the given tool.
1015    ///
1016    /// # Panics
1017    /// Panics if the tool argument schema cannot be serialized.
1018    pub fn new(tool: T) -> Self {
1019        let schema = serde_json::to_value(schemars::schema_for!(T::Arguments))
1020            .expect("failed to serialize tool schema");
1021        let name = tool.name().to_string();
1022        let positional_args = detect_positional_args(&schema);
1023        let stdin_arg = detect_stdin_arg(&schema);
1024        let help = schema_to_help(&schema);
1025
1026        Self {
1027            tool: Arc::new(tool),
1028            schema,
1029            name,
1030            positional_args,
1031            stdin_arg,
1032            help,
1033        }
1034    }
1035}
1036
1037impl<T> IpcCommand for IpcToolCommand<T>
1038where
1039    T: Tool + Clone + Send + Sync + 'static,
1040    T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
1041{
1042    type Args = HashMap<String, Value>;
1043    type Response = CommandEnvelope;
1044
1045    fn name(&self) -> Cow<'static, str> {
1046        Cow::Owned(self.name.clone())
1047    }
1048
1049    fn positional_args(&self) -> Cow<'static, [Cow<'static, str>]> {
1050        if self.positional_args.is_empty() {
1051            Cow::Borrowed(&[])
1052        } else {
1053            Cow::Owned(
1054                self.positional_args
1055                    .iter()
1056                    .map(|s| Cow::Owned(s.clone()))
1057                    .collect(),
1058            )
1059        }
1060    }
1061
1062    fn stdin_arg(&self) -> Option<Cow<'static, str>> {
1063        self.stdin_arg.clone().map(Cow::Owned)
1064    }
1065
1066    async fn handle(&self, args: Self::Args) -> CommandEnvelope {
1067        let cli_args = flatten_args_to_cli(&args);
1068
1069        // Handle help flags
1070        if has_help_flag(&cli_args) {
1071            return CommandEnvelope::success(CommandPayload::Text {
1072                content: self.help.clone(),
1073            });
1074        }
1075
1076        // Parse CLI args to JSON
1077        let json_args = match cli_to_json(&self.schema, &cli_args) {
1078            Ok(args) => args,
1079            Err(e) => {
1080                let message = e.to_string();
1081                return CommandEnvelope::failure(tool_usage_error(
1082                    message.as_str(),
1083                    self.name.as_str(),
1084                ));
1085            }
1086        };
1087
1088        // Deserialize and call tool
1089        let parsed: T::Arguments = match serde_json::from_value(json_args) {
1090            Ok(args) => args,
1091            Err(e) => {
1092                let message = prefix_error("invalid arguments: ", &e);
1093                return CommandEnvelope::failure(tool_usage_error(
1094                    message.as_str(),
1095                    self.name.as_str(),
1096                ));
1097            }
1098        };
1099
1100        match self.tool.call(parsed).await {
1101            Ok(output) => match tool_output_to_payload(output) {
1102                Ok(Some(payload)) => CommandEnvelope::success(payload),
1103                Ok(None) => CommandEnvelope::success_empty(),
1104                Err(error) => CommandEnvelope::failure(error),
1105            },
1106            Err(e) => CommandEnvelope::failure(e.to_string()),
1107        }
1108    }
1109}
1110
1111/// Registers a tool directly with the IPC router (no global state).
1112///
1113/// This is the preferred way to register tools. The tool is wrapped
1114/// in an IPC command and added to the router.
1115///
1116/// # Example
1117///
1118/// ```rust,ignore
1119/// use aither_sandbox::command::register_tool_direct;
1120/// use heel::IpcRouter;
1121///
1122/// let router = IpcRouter::new();
1123/// let router = register_tool_direct(router, my_tool);
1124/// ```
1125pub fn register_tool_direct<T>(router: heel::IpcRouter, tool: T) -> heel::IpcRouter
1126where
1127    T: Tool + Send + Sync + Clone + Default + 'static,
1128    T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
1129{
1130    router.register(IpcToolCommand::new(tool))
1131}
1132
1133/// Converts CLI arguments to JSON using schema information.
1134///
1135/// Handles:
1136/// - Tagged enums (`#[serde(tag = "operation")]`) → subcommands
1137/// - Long options → `--flag value`, `--flag=value`, `--no-flag`
1138/// - Short options → `-f`, clusters like `-abc`, and values `-oVALUE` / `-o=VALUE`
1139/// - `--` to end option parsing
1140/// - Struct fields → `--flag value` or positional args
1141/// - Optional fields → optional flags
1142///
1143/// # Errors
1144///
1145/// Returns an error if the arguments don't match the schema.
1146pub fn cli_to_json(schema: &Value, args: &[String]) -> anyhow::Result<Value> {
1147    // Check if this is a tagged enum (oneOf with discriminator)
1148    if let Some(one_of) = schema.get("oneOf").and_then(Value::as_array) {
1149        // Look for serde tag annotation in schema
1150        if let Some(tag) = find_serde_tag(schema) {
1151            return parse_tagged_enum(schema, one_of, &tag, args);
1152        }
1153    }
1154
1155    // Otherwise treat as a simple object
1156    parse_object(schema, schema, args)
1157}
1158
1159/// Finds the serde tag field name from schema extensions.
1160fn find_serde_tag(schema: &Value) -> Option<String> {
1161    // Check for discriminator property (OpenAPI style)
1162    if let Some(disc) = schema.get("discriminator")
1163        && let Some(prop) = disc.get("propertyName").and_then(Value::as_str)
1164    {
1165        return Some(prop.to_string());
1166    }
1167
1168    // Check oneOf variants for common const field (serde tag pattern)
1169    if let Some(variants) = schema.get("oneOf").and_then(Value::as_array)
1170        && let Some(first) = variants.first()
1171        && let Some(props) = first.get("properties").and_then(Value::as_object)
1172    {
1173        for (name, prop) in props {
1174            // If this property has a const value, it's likely the tag
1175            if prop.get("const").is_some() || prop.get("enum").is_some() {
1176                return Some(name.clone());
1177            }
1178        }
1179    }
1180
1181    None
1182}
1183
1184/// Parses a tagged enum from CLI arguments.
1185fn parse_tagged_enum(
1186    root_schema: &Value,
1187    variants: &[Value],
1188    tag: &str,
1189    args: &[String],
1190) -> anyhow::Result<Value> {
1191    let args = if args.first().map(std::string::String::as_str) == Some("--") {
1192        &args[1..]
1193    } else {
1194        args
1195    };
1196
1197    if args.is_empty() {
1198        let variant_names: Vec<_> = variants
1199            .iter()
1200            .filter_map(|v| get_variant_name(v, tag))
1201            .collect();
1202        anyhow::bail!("expected subcommand: {}", variant_names.join(", "));
1203    }
1204
1205    let subcommand = &args[0];
1206    let remaining = &args[1..];
1207
1208    // Find matching variant
1209    for variant in variants {
1210        if let Some(name) = get_variant_name(variant, tag)
1211            && name.eq_ignore_ascii_case(subcommand)
1212        {
1213            let mut variant_schema = variant.clone();
1214            remove_required_field(&mut variant_schema, tag);
1215            // Parse the variant's fields
1216            let mut result = parse_object(root_schema, &variant_schema, remaining)?;
1217
1218            // Add the tag field
1219            if let Value::Object(ref mut map) = result {
1220                map.insert(tag.to_string(), Value::String(name));
1221            }
1222
1223            return Ok(result);
1224        }
1225    }
1226
1227    let variant_names: Vec<_> = variants
1228        .iter()
1229        .filter_map(|v| get_variant_name(v, tag))
1230        .collect();
1231    anyhow::bail!(
1232        "unknown subcommand '{}', expected one of: {}",
1233        subcommand,
1234        variant_names.join(", ")
1235    );
1236}
1237
1238fn remove_required_field(schema: &mut Value, field: &str) {
1239    if let Some(required) = schema.get_mut("required").and_then(Value::as_array_mut) {
1240        required.retain(|entry| entry.as_str() != Some(field));
1241    }
1242}
1243
1244/// Gets the variant name from a schema object.
1245fn get_variant_name(schema: &Value, tag: &str) -> Option<String> {
1246    // Look for const value in tag property
1247    if let Some(props) = schema.get("properties").and_then(Value::as_object)
1248        && let Some(prop) = props.get(tag)
1249    {
1250        if let Some(const_val) = prop.get("const").and_then(Value::as_str) {
1251            return Some(const_val.to_string());
1252        }
1253        // Also check enum with single value
1254        if let Some(enum_vals) = prop.get("enum").and_then(Value::as_array)
1255            && enum_vals.len() == 1
1256        {
1257            return enum_vals[0].as_str().map(String::from);
1258        }
1259    }
1260
1261    // Fallback: use title
1262    schema
1263        .get("title")
1264        .and_then(Value::as_str)
1265        .map(String::from)
1266}
1267
1268/// Returns true if args contain -h/--help before "--".
1269fn has_help_flag(args: &[String]) -> bool {
1270    let args = if args.first().map(std::string::String::as_str) == Some("--") {
1271        &args[1..]
1272    } else {
1273        args
1274    };
1275    let mut end_of_options = false;
1276    for arg in args {
1277        if end_of_options {
1278            break;
1279        }
1280        if arg == "--" {
1281            end_of_options = true;
1282            continue;
1283        }
1284        if arg == "--help" || arg == "-h" {
1285            return true;
1286        }
1287        if arg.starts_with('-') && !arg.starts_with("--") && arg.chars().skip(1).any(|c| c == 'h') {
1288            return true;
1289        }
1290    }
1291    false
1292}
1293
1294fn build_short_option_maps(
1295    properties: &serde_json::Map<String, Value>,
1296) -> (HashMap<char, String>, HashMap<String, char>) {
1297    let mut taken = HashSet::new();
1298    taken.insert('h');
1299    let mut short_to_field = HashMap::new();
1300    let mut field_to_short = HashMap::new();
1301
1302    for field in properties.keys() {
1303        let long = field.replace('_', "-");
1304        if let Some(ch) = pick_short_option(&long, &taken) {
1305            taken.insert(ch);
1306            short_to_field.insert(ch, field.clone());
1307            field_to_short.insert(field.clone(), ch);
1308        }
1309    }
1310
1311    (short_to_field, field_to_short)
1312}
1313
1314fn pick_short_option(long: &str, taken: &HashSet<char>) -> Option<char> {
1315    for ch in long.chars() {
1316        if !ch.is_ascii_alphabetic() {
1317            continue;
1318        }
1319        let lower = ch.to_ascii_lowercase();
1320        if !taken.contains(&lower) {
1321            return Some(lower);
1322        }
1323    }
1324    None
1325}
1326
1327/// Finds the most similar option name for typo suggestions.
1328fn find_similar_option<'a>(input: &str, options: impl Iterator<Item = &'a str>) -> Option<String> {
1329    let input_lower = input.to_lowercase().replace('_', "-");
1330    options
1331        .map(|opt| (opt, strsim::levenshtein(&input_lower, &opt.to_lowercase())))
1332        .filter(|(_, dist)| *dist <= 2) // Only suggest if edit distance <= 2
1333        .min_by_key(|(_, dist)| *dist)
1334        .map(|(opt, _)| opt.to_string())
1335}
1336
1337/// Parses an object schema from CLI arguments.
1338fn parse_object(root_schema: &Value, schema: &Value, args: &[String]) -> anyhow::Result<Value> {
1339    let args = if args.first().map(std::string::String::as_str) == Some("--") {
1340        &args[1..]
1341    } else {
1342        args
1343    };
1344    let schema = ObjectParseSchema::new(root_schema, schema);
1345    let mut state = ObjectParseState::default();
1346    let mut i = 0;
1347    while i < args.len() {
1348        let arg = &args[i];
1349
1350        if !state.end_of_options && arg == "--" {
1351            state.end_of_options = true;
1352            i += 1;
1353            continue;
1354        }
1355
1356        if !state.end_of_options && arg.starts_with("--") {
1357            parse_long_option(root_schema, args, &mut i, &schema, &mut state)?;
1358        } else if !state.end_of_options && arg.starts_with('-') && arg.len() > 1 && arg != "-" {
1359            parse_short_options(
1360                root_schema,
1361                arg,
1362                args,
1363                &mut i,
1364                &schema.properties,
1365                &schema.short_to_field,
1366                &mut state.result,
1367            )?;
1368        } else {
1369            parse_positional_arg(root_schema, &schema, &mut state, arg)?;
1370        }
1371
1372        i += 1;
1373    }
1374
1375    if schema.command_capture_enabled
1376        && !state.seen_positionals.is_empty()
1377        && !state.result.contains_key("command")
1378    {
1379        state.result.insert(
1380            "command".to_string(),
1381            Value::String(state.seen_positionals.join(" ")),
1382        );
1383    }
1384
1385    for req in &schema.required {
1386        if !state.result.contains_key(req) {
1387            anyhow::bail!("missing required argument: {req}");
1388        }
1389    }
1390
1391    Ok(Value::Object(state.result.into_iter().collect()))
1392}
1393
1394struct ObjectParseSchema {
1395    properties: serde_json::Map<String, Value>,
1396    required: Vec<String>,
1397    positional_fields: Vec<String>,
1398    command_capture_enabled: bool,
1399    short_to_field: HashMap<char, String>,
1400    long_names: Vec<String>,
1401}
1402
1403impl ObjectParseSchema {
1404    fn new(root_schema: &Value, schema: &Value) -> Self {
1405        let resolved = resolved_schema(root_schema, schema);
1406        let properties = resolved
1407            .get("properties")
1408            .and_then(Value::as_object)
1409            .cloned()
1410            .unwrap_or_default();
1411        let required: Vec<String> = resolved
1412            .get("required")
1413            .and_then(Value::as_array)
1414            .map(|arr| {
1415                arr.iter()
1416                    .filter_map(Value::as_str)
1417                    .map(String::from)
1418                    .collect()
1419            })
1420            .unwrap_or_default();
1421        let positional_fields = positional_fields(root_schema, &properties, &required);
1422        let command_capture_enabled = properties
1423            .get("command")
1424            .is_some_and(|schema| get_instance_type(root_schema, schema) == Some("string"));
1425        let (short_to_field, _) = build_short_option_maps(&properties);
1426        let long_names = properties.keys().map(|k| k.replace('_', "-")).collect();
1427        Self {
1428            properties,
1429            required,
1430            positional_fields,
1431            command_capture_enabled,
1432            short_to_field,
1433            long_names,
1434        }
1435    }
1436}
1437
1438#[derive(Default)]
1439struct ObjectParseState {
1440    result: HashMap<String, Value>,
1441    positional_idx: usize,
1442    seen_positionals: Vec<String>,
1443    end_of_options: bool,
1444}
1445
1446fn positional_fields(
1447    root_schema: &Value,
1448    properties: &serde_json::Map<String, Value>,
1449    required: &[String],
1450) -> Vec<String> {
1451    required
1452        .iter()
1453        .filter(|name| {
1454            properties.get(name.as_str()).is_none_or(|prop_schema| {
1455                get_instance_type(root_schema, prop_schema) != Some("array")
1456            })
1457        })
1458        .cloned()
1459        .collect()
1460}
1461
1462fn parse_positional_arg(
1463    root_schema: &Value,
1464    schema: &ObjectParseSchema,
1465    state: &mut ObjectParseState,
1466    arg: &str,
1467) -> anyhow::Result<()> {
1468    if state.positional_idx < schema.positional_fields.len() {
1469        let field_name = &schema.positional_fields[state.positional_idx];
1470        if let Some(prop_schema) = schema.properties.get(field_name) {
1471            let prop_type = get_instance_type(root_schema, prop_schema);
1472            state
1473                .result
1474                .insert(field_name.clone(), parse_value(arg, prop_type));
1475        }
1476        state.positional_idx += 1;
1477        state.seen_positionals.push(arg.to_string());
1478    } else if schema.command_capture_enabled {
1479        state.seen_positionals.push(arg.to_string());
1480    } else {
1481        anyhow::bail!("unexpected positional argument: {arg}");
1482    }
1483    Ok(())
1484}
1485
1486fn parse_long_option(
1487    root_schema: &Value,
1488    args: &[String],
1489    i: &mut usize,
1490    schema: &ObjectParseSchema,
1491    state: &mut ObjectParseState,
1492) -> anyhow::Result<()> {
1493    let arg = &args[*i];
1494    let flag = &arg[2..];
1495    let (mut name, value) = flag.find('=').map_or_else(
1496        || (flag.to_string(), None),
1497        |eq_pos| {
1498            (
1499                flag[..eq_pos].to_string(),
1500                Some(flag[eq_pos + 1..].to_string()),
1501            )
1502        },
1503    );
1504    name = name.replace('_', "-");
1505    let (normalized_name, negated) = name.strip_prefix("no-").map_or_else(
1506        || (name.clone(), false),
1507        |stripped| (stripped.to_string(), true),
1508    );
1509    name = normalized_name;
1510    let field_name = name.replace('-', "_");
1511    let Some(prop_schema) = schema.properties.get(&field_name) else {
1512        return bail_unknown_long_option(&name, &schema.long_names);
1513    };
1514    let parsed_value =
1515        parse_long_option_value(root_schema, args, i, &name, value, negated, prop_schema)?;
1516    insert_value(
1517        root_schema,
1518        &mut state.result,
1519        &field_name,
1520        parsed_value,
1521        prop_schema,
1522    );
1523    Ok(())
1524}
1525
1526fn parse_long_option_value(
1527    root_schema: &Value,
1528    args: &[String],
1529    i: &mut usize,
1530    name: &str,
1531    value: Option<String>,
1532    negated: bool,
1533    prop_schema: &Value,
1534) -> anyhow::Result<Value> {
1535    let prop_type = get_instance_type(root_schema, prop_schema);
1536    if negated && prop_type != Some("boolean") {
1537        anyhow::bail!("--no-{name} is only valid for boolean options");
1538    }
1539    if prop_type == Some("boolean") {
1540        if negated && value.is_some() {
1541            anyhow::bail!("unexpected value for --no-{name}");
1542        }
1543        return Ok(value.map_or(Value::Bool(!negated), |v| parse_value(&v, prop_type)));
1544    }
1545    let val = value.or_else(|| {
1546        *i += 1;
1547        args.get(*i).cloned()
1548    });
1549    val.map_or_else(
1550        || anyhow::bail!("missing value for --{name}"),
1551        |v| Ok(parse_value(&v, prop_type)),
1552    )
1553}
1554
1555fn bail_unknown_long_option(name: &str, long_names: &[String]) -> anyhow::Result<()> {
1556    let suggestion = find_similar_option(name, long_names.iter().map(String::as_str));
1557    if let Some(similar) = suggestion {
1558        anyhow::bail!("unknown option: --{name}. Did you mean --{similar}?");
1559    }
1560    anyhow::bail!("unknown option: --{name}");
1561}
1562
1563fn parse_short_options(
1564    root_schema: &Value,
1565    arg: &str,
1566    args: &[String],
1567    i: &mut usize,
1568    properties: &serde_json::Map<String, Value>,
1569    short_to_field: &HashMap<char, String>,
1570    result: &mut HashMap<String, Value>,
1571) -> anyhow::Result<()> {
1572    let mut cluster = &arg[1..];
1573    let mut value_from_eq = None;
1574    if let Some(eq_pos) = cluster.find('=') {
1575        value_from_eq = Some(cluster[eq_pos + 1..].to_string());
1576        cluster = &cluster[..eq_pos];
1577    }
1578
1579    let mut chars = cluster.chars().peekable();
1580    while let Some(ch) = chars.next() {
1581        let field_name = short_to_field
1582            .get(&ch)
1583            .ok_or_else(|| anyhow::anyhow!("unknown option: -{ch}"))?
1584            .clone();
1585        let prop_schema = properties
1586            .get(&field_name)
1587            .ok_or_else(|| anyhow::anyhow!("unknown option: -{ch}"))?;
1588        let prop_type = get_instance_type(root_schema, prop_schema);
1589
1590        if prop_type == Some("boolean") {
1591            if chars.peek().is_none() {
1592                if let Some(v) = value_from_eq.take() {
1593                    let parsed = parse_value(&v, prop_type);
1594                    insert_value(root_schema, result, &field_name, parsed, prop_schema);
1595                } else {
1596                    insert_value(
1597                        root_schema,
1598                        result,
1599                        &field_name,
1600                        Value::Bool(true),
1601                        prop_schema,
1602                    );
1603                }
1604            } else {
1605                if value_from_eq.is_some() {
1606                    anyhow::bail!("unexpected value for -{ch}");
1607                }
1608                insert_value(
1609                    root_schema,
1610                    result,
1611                    &field_name,
1612                    Value::Bool(true),
1613                    prop_schema,
1614                );
1615            }
1616            continue;
1617        }
1618
1619        let value = if let Some(v) = value_from_eq.take() {
1620            if chars.peek().is_some() {
1621                anyhow::bail!("unexpected value for -{ch}");
1622            }
1623            v
1624        } else if chars.peek().is_some() {
1625            let rest: String = chars.collect();
1626            rest
1627        } else {
1628            *i += 1;
1629            args.get(*i)
1630                .cloned()
1631                .ok_or_else(|| anyhow::anyhow!("missing value for -{ch}"))?
1632        };
1633
1634        let parsed = parse_value(&value, prop_type);
1635        insert_value(root_schema, result, &field_name, parsed, prop_schema);
1636        break;
1637    }
1638
1639    Ok(())
1640}
1641
1642fn insert_value(
1643    root_schema: &Value,
1644    result: &mut HashMap<String, Value>,
1645    field_name: &str,
1646    value: Value,
1647    prop_schema: &Value,
1648) {
1649    if get_instance_type(root_schema, prop_schema) == Some("array") {
1650        if let Some(Value::Array(existing)) = result.get_mut(field_name) {
1651            match value {
1652                Value::Array(mut items) => existing.append(&mut items),
1653                other => existing.push(other),
1654            }
1655        } else {
1656            let mut items = Vec::new();
1657            match value {
1658                Value::Array(mut arr) => items.append(&mut arr),
1659                other => items.push(other),
1660            }
1661            result.insert(field_name.to_string(), Value::Array(items));
1662        }
1663    } else {
1664        result.insert(field_name.to_string(), value);
1665    }
1666}
1667
1668/// Gets the instance type from a schema.
1669/// Handles both simple types and Option<T>.
1670fn get_instance_type<'a>(root_schema: &'a Value, schema: &'a Value) -> Option<&'a str> {
1671    let schema = resolved_schema(root_schema, schema);
1672    match schema.get("type") {
1673        // Direct string type: "type": "integer"
1674        Some(Value::String(t)) => Some(t.as_str()),
1675
1676        // Array of types (schemars 1.0 for Option<T>): "type": ["integer", "null"]
1677        Some(Value::Array(types)) => {
1678            // Find the non-null type
1679            for t in types {
1680                if let Some(s) = t.as_str()
1681                    && s != "null"
1682                {
1683                    return Some(s);
1684                }
1685            }
1686            None
1687        }
1688
1689        // No direct type - try anyOf/oneOf (older schemars or complex types)
1690        None => {
1691            let variants = schema
1692                .get("anyOf")
1693                .or_else(|| schema.get("oneOf"))
1694                .and_then(Value::as_array)?;
1695
1696            for variant in variants {
1697                if let Some(t) = variant.get("type").and_then(Value::as_str)
1698                    && t != "null"
1699                {
1700                    return Some(t);
1701                }
1702            }
1703            None
1704        }
1705
1706        _ => None,
1707    }
1708}
1709
1710fn resolved_schema<'a>(root_schema: &'a Value, schema: &'a Value) -> &'a Value {
1711    let mut current = schema;
1712    while let Some(reference) = current.get("$ref").and_then(Value::as_str) {
1713        let Some(next) = resolve_local_ref(root_schema, reference) else {
1714            break;
1715        };
1716        if std::ptr::eq(current, next) {
1717            break;
1718        }
1719        current = next;
1720    }
1721    current
1722}
1723
1724fn resolve_local_ref<'a>(root_schema: &'a Value, reference: &str) -> Option<&'a Value> {
1725    let pointer = reference.strip_prefix("#/")?;
1726    let mut current = root_schema;
1727    for segment in pointer.split('/') {
1728        let segment = segment.replace("~1", "/").replace("~0", "~");
1729        current = current.get(segment.as_str())?;
1730    }
1731    Some(current)
1732}
1733
1734/// Parses a string value according to expected type.
1735fn parse_value(s: &str, expected_type: Option<&str>) -> Value {
1736    match expected_type {
1737        Some("integer") => s
1738            .parse::<i64>()
1739            .map_or_else(|_| Value::String(s.to_string()), Value::from),
1740        Some("number") => s
1741            .parse::<f64>()
1742            .map_or_else(|_| Value::String(s.to_string()), Value::from),
1743        Some("boolean") => match s.to_lowercase().as_str() {
1744            "true" | "1" | "yes" => Value::Bool(true),
1745            "false" | "0" | "no" => Value::Bool(false),
1746            _ => Value::String(s.to_string()),
1747        },
1748        Some("array") => {
1749            // Try parsing as JSON array, fallback to single-element array
1750            serde_json::from_str(s)
1751                .unwrap_or_else(|_| Value::Array(vec![Value::String(s.to_string())]))
1752        }
1753        Some("object") => {
1754            // Try parsing as JSON object
1755            serde_json::from_str(s).unwrap_or_else(|_| Value::String(s.to_string()))
1756        }
1757        _ => Value::String(s.to_string()),
1758    }
1759}
1760
1761/// Generates help text from a JSON schema.
1762#[must_use]
1763pub fn schema_to_help(schema: &Value) -> String {
1764    let mut help = String::new();
1765
1766    // Title and description
1767    if let Some(title) = schema.get("title").and_then(Value::as_str) {
1768        help.push_str(title);
1769        help.push('\n');
1770    }
1771    if let Some(desc) = schema.get("description").and_then(Value::as_str) {
1772        help.push_str(desc);
1773        help.push('\n');
1774    }
1775
1776    help.push_str("\nUsage:\n");
1777
1778    // Check for tagged enum (subcommands)
1779    if let Some(variants) = schema.get("oneOf").and_then(Value::as_array)
1780        && let Some(tag) = find_serde_tag(schema)
1781    {
1782        help.push_str("  <subcommand> [options]\n\n");
1783        help.push_str("Subcommands:\n");
1784
1785        for variant in variants {
1786            if let Some(name) = get_variant_name(variant, &tag) {
1787                help.push_str("  ");
1788                help.push_str(name.as_str());
1789                if let Some(desc) = variant.get("description").and_then(Value::as_str) {
1790                    help.push_str(" - ");
1791                    help.push_str(desc);
1792                }
1793                help.push('\n');
1794            }
1795        }
1796        help.push_str("\nOptions:\n  -h, --help  Show help\n");
1797        return help;
1798    }
1799
1800    // Simple object
1801    if let Some(props) = schema.get("properties").and_then(Value::as_object) {
1802        let required: Vec<&str> = schema
1803            .get("required")
1804            .and_then(Value::as_array)
1805            .map(|arr| arr.iter().filter_map(Value::as_str).collect())
1806            .unwrap_or_default();
1807
1808        // Show positional usage: only non-array required fields are positional
1809        let positional: Vec<_> = required
1810            .iter()
1811            .filter(|n| {
1812                props
1813                    .get(**n)
1814                    .is_none_or(|s| get_instance_type(s, s) != Some("array"))
1815            })
1816            .map(|n| render_positional_usage(n))
1817            .collect();
1818        // Show required array fields as repeatable flags in usage
1819        let repeatable: Vec<_> = required
1820            .iter()
1821            .filter(|n| {
1822                props
1823                    .get(**n)
1824                    .is_some_and(|s| get_instance_type(s, s) == Some("array"))
1825            })
1826            .map(|n| render_repeatable_usage(n))
1827            .collect();
1828
1829        let mut usage_parts = Vec::new();
1830        if !positional.is_empty() {
1831            usage_parts.push(positional.join(" "));
1832        }
1833        for r in &repeatable {
1834            usage_parts.push(r.clone());
1835        }
1836        usage_parts.push("[options]".to_string());
1837        let usage = usage_parts.join(" ");
1838        help.push_str("  ");
1839        push_help_line(&mut help, usage.as_str());
1840
1841        help.push_str("\nOptions:\n  -h, --help  Show help\n");
1842        help.push_str("\nArguments:\n");
1843
1844        let (_, field_to_short) = build_short_option_maps(props);
1845
1846        for (name, prop) in props {
1847            let is_required = required.contains(&name.as_str());
1848            let is_array = get_instance_type(prop, prop) == Some("array");
1849            let flag = name.replace('_', "-");
1850
1851            let short = field_to_short.get(name).copied();
1852            help.push_str(render_flag_prefix(flag.as_str(), short).as_str());
1853            if is_array {
1854                help.push_str(" <value>  (repeatable");
1855                if is_required {
1856                    help.push_str(", required");
1857                }
1858                help.push(')');
1859            } else if is_required {
1860                help.push_str(" (required)");
1861            }
1862
1863            if let Some(desc) = prop.get("description").and_then(Value::as_str) {
1864                help.push_str("\n      ");
1865                help.push_str(desc);
1866            }
1867            help.push('\n');
1868        }
1869    }
1870
1871    help
1872}
1873
1874#[cfg(test)]
1875mod tests {
1876    use super::*;
1877    use schemars::JsonSchema;
1878    use serde::Deserialize;
1879
1880    #[derive(Debug, Deserialize, JsonSchema)]
1881    struct SimpleArgs {
1882        #[schemars(description = "The input file path")]
1883        path: String,
1884        #[schemars(description = "Number of lines to read")]
1885        count: Option<i32>,
1886    }
1887
1888    #[test]
1889    fn test_parse_simple_args() {
1890        let schema = schemars::schema_for!(SimpleArgs);
1891        let schema = serde_json::to_value(schema).unwrap();
1892
1893        // Positional
1894        let result = cli_to_json(&schema, &["foo.txt".to_string()]).unwrap();
1895        assert_eq!(result["path"], "foo.txt");
1896
1897        // Named
1898        let result = cli_to_json(&schema, &["--path".to_string(), "bar.txt".to_string()]).unwrap();
1899        assert_eq!(result["path"], "bar.txt");
1900
1901        // With optional
1902        let result = cli_to_json(
1903            &schema,
1904            &[
1905                "--path".to_string(),
1906                "baz.txt".to_string(),
1907                "--count".to_string(),
1908                "10".to_string(),
1909            ],
1910        )
1911        .unwrap();
1912        assert_eq!(result["path"], "baz.txt");
1913        assert_eq!(result["count"], 10);
1914    }
1915
1916    #[test]
1917    fn test_short_flags() {
1918        let schema = schemars::schema_for!(SimpleArgs);
1919        let schema = serde_json::to_value(schema).unwrap();
1920
1921        let result = cli_to_json(
1922            &schema,
1923            &[
1924                "-p".to_string(),
1925                "short.txt".to_string(),
1926                "-c".to_string(),
1927                "7".to_string(),
1928            ],
1929        )
1930        .unwrap();
1931        assert_eq!(result["path"], "short.txt");
1932        assert_eq!(result["count"], 7);
1933    }
1934
1935    #[derive(Debug, Deserialize, JsonSchema)]
1936    struct ClusterArgs {
1937        /// Verbose output
1938        verbose: bool,
1939        /// Output path
1940        output: String,
1941    }
1942
1943    #[test]
1944    fn test_short_cluster_with_value() {
1945        let schema = schemars::schema_for!(ClusterArgs);
1946        let schema = serde_json::to_value(schema).unwrap();
1947
1948        let result = cli_to_json(&schema, &["-vofile.txt".to_string()]).unwrap();
1949        assert_eq!(result["verbose"], true);
1950        assert_eq!(result["output"], "file.txt");
1951    }
1952
1953    #[test]
1954    fn test_leading_separator_stripped() {
1955        let schema = schemars::schema_for!(SimpleArgs);
1956        let schema = serde_json::to_value(schema).unwrap();
1957
1958        // Leading "--" from `heel ipc` is stripped; flags still work after it
1959        let result = cli_to_json(
1960            &schema,
1961            &[
1962                "--".to_string(),
1963                "--path".to_string(),
1964                "foo.txt".to_string(),
1965            ],
1966        )
1967        .unwrap();
1968        assert_eq!(result["path"], "foo.txt");
1969    }
1970
1971    #[test]
1972    fn test_end_of_options_after_separator() {
1973        let schema = schemars::schema_for!(SimpleArgs);
1974        let schema = serde_json::to_value(schema).unwrap();
1975
1976        // Double "--": first is the `heel ipc` separator, second is end-of-options
1977        let result = cli_to_json(
1978            &schema,
1979            &["--".to_string(), "--".to_string(), "-dash.txt".to_string()],
1980        )
1981        .unwrap();
1982        assert_eq!(result["path"], "-dash.txt");
1983    }
1984
1985    #[derive(Debug, Deserialize, JsonSchema)]
1986    struct TwoPositionalArgs {
1987        /// First required arg
1988        first: String,
1989        /// Second required arg
1990        second: String,
1991    }
1992
1993    #[derive(Debug, Deserialize, JsonSchema)]
1994    #[serde(tag = "operation", rename_all = "snake_case")]
1995    enum TaggedOperationArgs {
1996        Read { path: String },
1997        Write { path: String, content: String },
1998    }
1999
2000    #[derive(Debug, Deserialize, JsonSchema)]
2001    #[serde(tag = "kind", rename_all = "snake_case")]
2002    enum NestedTriggerArgs {
2003        Webhook,
2004        Event { event_name: String },
2005    }
2006
2007    #[derive(Debug, Deserialize, JsonSchema)]
2008    struct NestedObjectArgs {
2009        name: String,
2010        trigger: NestedTriggerArgs,
2011    }
2012
2013    #[test]
2014    fn test_multiple_positional_args() {
2015        let schema = schemars::schema_for!(TwoPositionalArgs);
2016        let schema = serde_json::to_value(schema).unwrap();
2017
2018        // Both as positional
2019        let result = cli_to_json(&schema, &["hello".to_string(), "world".to_string()]).unwrap();
2020        assert_eq!(result["first"], "hello");
2021        assert_eq!(result["second"], "world");
2022
2023        // Mix positional and named
2024        let result = cli_to_json(
2025            &schema,
2026            &[
2027                "hello".to_string(),
2028                "--second".to_string(),
2029                "world".to_string(),
2030            ],
2031        )
2032        .unwrap();
2033        assert_eq!(result["first"], "hello");
2034        assert_eq!(result["second"], "world");
2035    }
2036
2037    #[test]
2038    fn test_tagged_enum_subcommand_parsing() {
2039        let schema = schemars::schema_for!(TaggedOperationArgs);
2040        let schema = serde_json::to_value(schema).unwrap();
2041
2042        let result = cli_to_json(
2043            &schema,
2044            &[
2045                "read".to_string(),
2046                "--path".to_string(),
2047                "foo.txt".to_string(),
2048            ],
2049        )
2050        .unwrap();
2051        assert_eq!(result["operation"], "read");
2052        assert_eq!(result["path"], "foo.txt");
2053
2054        let err = cli_to_json(
2055            &schema,
2056            &[
2057                "write".to_string(),
2058                "--path".to_string(),
2059                "foo.txt".to_string(),
2060            ],
2061        )
2062        .unwrap_err();
2063        assert!(
2064            err.to_string()
2065                .contains("missing required argument: content"),
2066            "got: {err}"
2067        );
2068    }
2069
2070    #[test]
2071    fn test_nested_ref_object_flag_parsing() {
2072        let schema = schemars::schema_for!(NestedObjectArgs);
2073        let schema = serde_json::to_value(schema).unwrap();
2074
2075        let result = cli_to_json(
2076            &schema,
2077            &[
2078                "--name".to_string(),
2079                "demo".to_string(),
2080                "--trigger".to_string(),
2081                "{\"kind\":\"webhook\"}".to_string(),
2082            ],
2083        )
2084        .unwrap();
2085
2086        assert_eq!(result["name"], "demo");
2087        assert_eq!(result["trigger"]["kind"], "webhook");
2088    }
2089
2090    #[test]
2091    fn test_typo_suggestion() {
2092        let schema = schemars::schema_for!(SimpleArgs);
2093        let schema = serde_json::to_value(schema).unwrap();
2094
2095        // Typo in flag name -- deliberate, it is what the suggestion is for.
2096        let err = cli_to_json(&schema, &["--paht".to_string(), "foo.txt".to_string()]).unwrap_err();
2097        assert!(err.to_string().contains("Did you mean --path?"));
2098    }
2099
2100    #[test]
2101    fn test_schema_to_help() {
2102        let schema = schemars::schema_for!(SimpleArgs);
2103        let schema = serde_json::to_value(schema).unwrap();
2104        let help = schema_to_help(&schema);
2105
2106        assert!(help.contains("<path>")); // Shows positional usage
2107        assert!(help.contains("-p, --path"));
2108        assert!(help.contains("--path"));
2109        assert!(help.contains("-c, --count"));
2110        assert!(help.contains("--count"));
2111    }
2112
2113    #[test]
2114    fn test_tool_call_command_serialization() {
2115        // Simulate IPC params (key-value pairs from `heel ipc`)
2116        let json = r#"{"query": "rust async", "max": 5}"#;
2117        let tmp = tempfile::tempdir().unwrap();
2118        let registry = ToolRegistryBuilder::new().build(tmp.path());
2119        let cmd = ToolCallCommand::new("websearch", Arc::new(registry));
2120        let args: std::collections::HashMap<String, Value> = serde_json::from_str(json).unwrap();
2121
2122        // the tool name rides on the command, the wire carries only arguments
2123        assert_eq!(cmd.name(), "websearch");
2124        assert_eq!(args.len(), 2);
2125        assert_eq!(args.get("query").unwrap(), "rust async");
2126        assert_eq!(args.get("max").unwrap(), 5);
2127
2128        let cli_args = flatten_args_to_cli(&args);
2129        assert!(cli_args.contains(&"--query".to_string()));
2130        assert!(cli_args.contains(&"rust async".to_string()));
2131    }
2132
2133    #[test]
2134    fn test_tool_call_command_name() {
2135        let tmp = tempfile::tempdir().unwrap();
2136        let registry = ToolRegistryBuilder::new().build(tmp.path());
2137        let cmd = ToolCallCommand::new("my_tool", Arc::new(registry));
2138        assert_eq!(cmd.name(), "my_tool");
2139    }
2140
2141    // ========================================================================
2142    // Array / repeated flag tests
2143    // ========================================================================
2144
2145    #[derive(Debug, Deserialize, JsonSchema)]
2146    struct AskUserLikeArgs {
2147        /// The question to ask
2148        question: String,
2149        /// Options to choose from
2150        options: Vec<String>,
2151        /// Allow multiple selections
2152        #[serde(default)]
2153        multi_select: bool,
2154    }
2155
2156    fn touch_test_arg_types() {
2157        let simple = SimpleArgs {
2158            path: "file.txt".to_string(),
2159            count: Some(1),
2160        };
2161        assert_eq!(simple.path, "file.txt");
2162        assert_eq!(simple.count, Some(1));
2163
2164        let cluster = ClusterArgs {
2165            verbose: true,
2166            output: "out.txt".to_string(),
2167        };
2168        assert!(cluster.verbose);
2169        assert_eq!(cluster.output, "out.txt");
2170
2171        let two = TwoPositionalArgs {
2172            first: "a".to_string(),
2173            second: "b".to_string(),
2174        };
2175        assert_eq!((two.first.as_str(), two.second.as_str()), ("a", "b"));
2176
2177        let read = TaggedOperationArgs::Read {
2178            path: "input.txt".to_string(),
2179        };
2180        let TaggedOperationArgs::Read { path } = read else {
2181            panic!("expected read operation");
2182        };
2183        assert_eq!(path, "input.txt");
2184
2185        let write = TaggedOperationArgs::Write {
2186            path: "output.txt".to_string(),
2187            content: "body".to_string(),
2188        };
2189        let TaggedOperationArgs::Write { path, content } = write else {
2190            panic!("expected write operation");
2191        };
2192        assert_eq!((path.as_str(), content.as_str()), ("output.txt", "body"));
2193
2194        let trigger = NestedTriggerArgs::Event {
2195            event_name: "ready".to_string(),
2196        };
2197        let NestedTriggerArgs::Event { event_name } = trigger else {
2198            panic!("expected event trigger");
2199        };
2200        assert_eq!(event_name, "ready");
2201
2202        let nested = NestedObjectArgs {
2203            name: "job".to_string(),
2204            trigger: NestedTriggerArgs::Webhook,
2205        };
2206        assert_eq!(nested.name, "job");
2207        assert!(matches!(nested.trigger, NestedTriggerArgs::Webhook));
2208
2209        let ask = AskUserLikeArgs {
2210            question: "Continue?".to_string(),
2211            options: vec!["yes".to_string()],
2212            multi_select: false,
2213        };
2214        assert_eq!(ask.question, "Continue?");
2215        assert_eq!(ask.options, ["yes"]);
2216        assert!(!ask.multi_select);
2217    }
2218
2219    #[test]
2220    fn test_repeated_flag_for_array() {
2221        touch_test_arg_types();
2222        let schema = schemars::schema_for!(AskUserLikeArgs);
2223        let schema = serde_json::to_value(schema).unwrap();
2224
2225        let result = cli_to_json(
2226            &schema,
2227            &[
2228                "--question".into(),
2229                "Pick one".into(),
2230                "--options".into(),
2231                "A".into(),
2232                "--options".into(),
2233                "B".into(),
2234                "--options".into(),
2235                "C".into(),
2236            ],
2237        )
2238        .unwrap();
2239
2240        assert_eq!(result["question"], "Pick one");
2241        assert_eq!(result["options"], serde_json::json!(["A", "B", "C"]));
2242    }
2243
2244    #[test]
2245    fn test_positional_then_repeated_flag() {
2246        let schema = schemars::schema_for!(AskUserLikeArgs);
2247        let schema = serde_json::to_value(schema).unwrap();
2248
2249        // question as positional, options as repeated flags
2250        let result = cli_to_json(
2251            &schema,
2252            &[
2253                "Pick one".into(),
2254                "--options".into(),
2255                "A".into(),
2256                "--options".into(),
2257                "B".into(),
2258            ],
2259        )
2260        .unwrap();
2261
2262        assert_eq!(result["question"], "Pick one");
2263        assert_eq!(result["options"], serde_json::json!(["A", "B"]));
2264    }
2265
2266    #[test]
2267    fn test_array_not_positional() {
2268        let schema = schemars::schema_for!(AskUserLikeArgs);
2269        let schema = serde_json::to_value(schema).unwrap();
2270
2271        // Only question should be positional, not options
2272        let positional = detect_positional_args(&schema);
2273        assert_eq!(positional, vec!["question"]);
2274    }
2275
2276    #[test]
2277    fn test_missing_required_array() {
2278        let schema = schemars::schema_for!(AskUserLikeArgs);
2279        let schema = serde_json::to_value(schema).unwrap();
2280
2281        // Provide question but no options -> should fail with clear message
2282        let err = cli_to_json(&schema, &["Pick one".into()]).unwrap_err();
2283        assert!(
2284            err.to_string()
2285                .contains("missing required argument: options"),
2286            "got: {err}"
2287        );
2288    }
2289
2290    #[test]
2291    fn test_boolean_flag_with_array() {
2292        let schema = schemars::schema_for!(AskUserLikeArgs);
2293        let schema = serde_json::to_value(schema).unwrap();
2294
2295        let result = cli_to_json(
2296            &schema,
2297            &[
2298                "--question".into(),
2299                "Pick many".into(),
2300                "--options".into(),
2301                "X".into(),
2302                "--options".into(),
2303                "Y".into(),
2304                "--multi-select".into(),
2305            ],
2306        )
2307        .unwrap();
2308
2309        assert_eq!(result["question"], "Pick many");
2310        assert_eq!(result["options"], serde_json::json!(["X", "Y"]));
2311        assert_eq!(result["multi_select"], true);
2312    }
2313
2314    // ========================================================================
2315    // Help text tests
2316    // ========================================================================
2317
2318    #[test]
2319    fn test_help_shows_array_as_repeatable() {
2320        let schema = schemars::schema_for!(AskUserLikeArgs);
2321        let schema = serde_json::to_value(schema).unwrap();
2322        let help = schema_to_help(&schema);
2323
2324        // Usage line should show options as repeatable flag, not positional
2325        assert!(
2326            help.contains("--options <value>..."),
2327            "usage should show --options as repeatable, got:\n{help}"
2328        );
2329        // question should be positional
2330        assert!(
2331            help.contains("<question>"),
2332            "usage should show <question> as positional, got:\n{help}"
2333        );
2334        // Arguments section should mark options as repeatable
2335        assert!(
2336            help.contains("repeatable"),
2337            "options should be marked repeatable, got:\n{help}"
2338        );
2339    }
2340
2341    // ========================================================================
2342    // Error message tests
2343    // ========================================================================
2344
2345    #[test]
2346    fn test_unknown_option_error() {
2347        let schema = schemars::schema_for!(SimpleArgs);
2348        let schema = serde_json::to_value(schema).unwrap();
2349
2350        let err = cli_to_json(&schema, &["--unknown".into(), "val".into()]).unwrap_err();
2351        assert!(err.to_string().contains("unknown option: --unknown"));
2352    }
2353
2354    #[test]
2355    fn test_unexpected_positional_error() {
2356        let schema = schemars::schema_for!(SimpleArgs);
2357        let schema = serde_json::to_value(schema).unwrap();
2358
2359        // Two positional args when only one is expected
2360        let err = cli_to_json(&schema, &["a.txt".into(), "extra".into()]).unwrap_err();
2361        assert!(err.to_string().contains("unexpected positional argument"));
2362    }
2363
2364    #[test]
2365    fn test_missing_value_error() {
2366        let schema = schemars::schema_for!(SimpleArgs);
2367        let schema = serde_json::to_value(schema).unwrap();
2368
2369        let err = cli_to_json(&schema, &["--path".into()]).unwrap_err();
2370        // path is consumed as positional, so we get missing required
2371        // Actually --path starts with --, so it enters the named path and needs a value
2372        assert!(err.to_string().contains("missing"), "got: {err}");
2373    }
2374
2375    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
2376    struct SessionLikeArgs {
2377        query: String,
2378        #[serde(default)]
2379        command: Option<String>,
2380    }
2381
2382    #[test]
2383    fn test_command_field_captures_single_positional_for_session_like_tools() {
2384        let schema = schemars::schema_for!(SessionLikeArgs);
2385        let schema = serde_json::to_value(schema).unwrap();
2386
2387        let value = cli_to_json(&schema, &["gold".into()]).unwrap();
2388        assert_eq!(value["query"], "gold");
2389        assert_eq!(value["command"], "gold");
2390    }
2391
2392    #[test]
2393    fn test_command_field_captures_multi_positional_for_session_like_tools() {
2394        let schema = schemars::schema_for!(SessionLikeArgs);
2395        let schema = serde_json::to_value(schema).unwrap();
2396
2397        let value = cli_to_json(&schema, &["abc123".into(), "search".into(), "gold".into()])
2398            .expect("session-like positional command should parse");
2399        assert_eq!(value["query"], "abc123");
2400        assert_eq!(value["command"], "abc123 search gold");
2401    }
2402
2403    // ========================================================================
2404    // ToolCallCommand args_to_cli with arrays
2405    // ========================================================================
2406
2407    #[test]
2408    fn test_tool_call_command_args_to_cli_with_array() {
2409        let tmp = tempfile::tempdir().unwrap();
2410        let registry = ToolRegistryBuilder::new().build(tmp.path());
2411        let _cmd = ToolCallCommand::new("ask_user", Arc::new(registry));
2412        let args: std::collections::HashMap<String, Value> =
2413            serde_json::from_value(serde_json::json!({
2414                "question": "Pick one",
2415                "options": ["A", "B", "C"]
2416            }))
2417            .unwrap();
2418
2419        let cli = flatten_args_to_cli(&args);
2420        // Should produce repeated --options flags
2421        let options_count = cli.iter().filter(|a| *a == "--options").count();
2422        assert_eq!(options_count, 3, "expected 3 --options flags, got: {cli:?}");
2423        assert!(cli.contains(&"A".to_string()));
2424        assert!(cli.contains(&"B".to_string()));
2425        assert!(cli.contains(&"C".to_string()));
2426    }
2427
2428    #[test]
2429    fn test_tool_call_command_raw_args_passthrough() {
2430        let tmp = tempfile::tempdir().unwrap();
2431        let registry = ToolRegistryBuilder::new().build(tmp.path());
2432        let _cmd = ToolCallCommand::new("ask_user", Arc::new(registry));
2433        // Simulates what `heel ipc` sends
2434        let args: std::collections::HashMap<String, Value> =
2435            serde_json::from_value(serde_json::json!({
2436                "args": ["--question", "Pick one", "--options", "A", "--options", "B"]
2437            }))
2438            .unwrap();
2439
2440        let cli = flatten_args_to_cli(&args);
2441        assert_eq!(
2442            cli,
2443            vec!["--question", "Pick one", "--options", "A", "--options", "B"]
2444        );
2445    }
2446
2447    #[test]
2448    fn test_flatten_args_to_cli_sorts_structured_keys_deterministically() {
2449        let args = serde_json::from_value::<HashMap<String, Value>>(serde_json::json!({
2450            "zebra": "last",
2451            "alpha": "first",
2452            "multi": ["x", "y"],
2453            "enabled": true
2454        }))
2455        .expect("structured args should deserialize");
2456
2457        let cli = flatten_args_to_cli(&args);
2458        assert_eq!(
2459            cli,
2460            vec![
2461                "--alpha",
2462                "first",
2463                "--enabled",
2464                "--multi",
2465                "x",
2466                "--multi",
2467                "y",
2468                "--zebra",
2469                "last"
2470            ]
2471        );
2472    }
2473
2474    #[tokio::test]
2475    async fn test_handle_large_output_write_failure_returns_error_message() {
2476        let tmp = tempfile::tempdir().unwrap();
2477        let output_dir = tmp.path().join("not-a-directory");
2478        std::fs::write(&output_dir, "occupied").unwrap();
2479        let output = Some(CommandPayload::Text {
2480            content: "x".repeat(INLINE_OUTPUT_LIMIT + 1),
2481        });
2482
2483        let result = handle_large_output(output, &output_dir).await;
2484        assert!(!result.ok);
2485        assert!(
2486            result
2487                .error
2488                .as_deref()
2489                .unwrap_or_default()
2490                .contains("failed to write output")
2491        );
2492    }
2493
2494    #[tokio::test]
2495    async fn test_ask_user_e2e_repeated_option() {
2496        use aither_core::llm::{Tool, ToolResult};
2497        use std::borrow::Cow;
2498
2499        #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
2500        struct Question {
2501            section: String,
2502            #[serde(rename = "question")]
2503            prompt: String,
2504            option: Vec<String>,
2505            #[serde(default)]
2506            multi_select: bool,
2507        }
2508
2509        #[derive(Debug, Clone, Deserialize, JsonSchema)]
2510        struct AskUserArgs {
2511            #[serde(default)]
2512            question: Option<String>,
2513            #[serde(default, alias = "options", alias = "choices")]
2514            option: Vec<String>,
2515            #[serde(default)]
2516            multi_select: bool,
2517            #[serde(default)]
2518            questions: Vec<Question>,
2519        }
2520
2521        #[derive(Debug, Clone)]
2522        struct FakeAskUser;
2523        impl Tool for FakeAskUser {
2524            fn name(&self) -> Cow<'static, str> {
2525                "ask_user".into()
2526            }
2527            type Arguments = AskUserArgs;
2528            type Res = ToolResult;
2529
2530            fn call(
2531                &self,
2532                args: Self::Arguments,
2533            ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send
2534            {
2535                // Return the parsed args as JSON so we can inspect
2536                std::future::ready(ToolResult::json(&serde_json::json!({
2537                    "question": args.question,
2538                    "option": args.option,
2539                    "multi_select": args.multi_select,
2540                    "questions": args.questions,
2541                })))
2542            }
2543        }
2544
2545        let tmp = tempfile::tempdir().unwrap();
2546        let mut builder = ToolRegistryBuilder::new();
2547        builder.configure_tool(FakeAskUser);
2548        let registry = std::sync::Arc::new(builder.build(tmp.path()));
2549
2550        // Simulate what `heel ipc` sends: all args in an "args" array
2551        let cmd = ToolCallCommand::new("ask_user", registry);
2552        let args = serde_json::from_value(serde_json::json!({
2553            "args": [
2554                "--", "--question", "你喜欢哪种薯条?",
2555                "--option", "原味", "--option", "番茄味", "--option", "芝士味"
2556            ]
2557        }))
2558        .unwrap();
2559
2560        let result = cmd.handle(args).await;
2561        tracing::debug!("result: {}", serde_json::to_string_pretty(&result).unwrap());
2562        assert!(result.ok, "command should succeed: {result:?}");
2563
2564        let Some(CommandPayload::Json { value: parsed }) = result.payload else {
2565            panic!("expected JSON payload, got {result:?}");
2566        };
2567        let options = parsed["option"].as_array().expect("option should be array");
2568        assert_eq!(options.len(), 3, "expected 3 options, got: {options:?}");
2569        assert_eq!(options[0], "原味");
2570        assert_eq!(options[1], "番茄味");
2571        assert_eq!(options[2], "芝士味");
2572    }
2573}