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