Skip to main content

agent_commander/
lib.rs

1//! Agent Commander - Main library interface
2//! A Rust library to control agents enclosed in CLI commands
3//!
4//! Supports multiple CLI agents:
5//! - claude: Anthropic Claude Code CLI
6//! - codex: OpenAI Codex CLI
7//! - opencode: OpenCode CLI
8//! - agent: @link-assistant/agent (OpenCode fork with native permission modes)
9//! - qwen: Qwen Code CLI
10//! - gemini: Gemini CLI
11
12pub mod cli_parser;
13pub mod command_builder;
14mod completion;
15pub mod executor;
16pub mod permissions;
17pub mod result_metadata;
18pub mod streaming;
19pub mod tools;
20pub mod tui;
21
22use serde_json::Value;
23use std::path::PathBuf;
24use std::time::{SystemTime, UNIX_EPOCH};
25use tokio::io::AsyncWriteExt;
26
27pub use cli_parser::{
28    parse_args, parse_start_agent_args, parse_stop_agent_args, show_start_agent_help,
29    show_stop_agent_help, validate_start_agent_options, validate_stop_agent_options,
30    StartAgentOptions, StopAgentOptions, ValidationResult,
31};
32
33pub use command_builder::{
34    build_agent_command, build_docker_stop_command, build_piped_command, build_screen_stop_command,
35    read_only_unsupported_error, supports_read_only, AgentCommandOptions,
36};
37
38pub use permissions::{
39    ask_scope, ask_unsupported_error, build_permission_response, normalize_permission_request,
40    permission_parity, supports_ask, NormalizedPermissionRequest, PermissionParityRow,
41    PermissionRelay, ASK_DECISIONS, ASK_SUPPORTED_TOOLS,
42};
43
44pub use executor::{
45    execute_command, execute_detached, setup_signal_handler, start_command, ExecutionResult,
46    ProcessHandle,
47};
48
49pub use result_metadata::{
50    build_normalized_result_metadata, BuildMetadataOptions, PricingInfo, ResultMetadata,
51};
52
53pub use streaming::{
54    create_input_stream, create_output_stream, parse_ndjson, parse_ndjson_line, stringify_ndjson,
55    stringify_ndjson_line, JsonInputStream, JsonOutputStream, ParseError,
56};
57
58pub use tools::{
59    get_tool, is_tool_supported, list_tools, AgentTool, ClaudeTool, CodexTool, OpencodeTool, Tool,
60    ToolRegistry,
61};
62
63/// Agent options for creating a controller
64#[derive(Debug, Clone, Default)]
65pub struct AgentOptions {
66    /// CLI tool to use (e.g., 'claude', 'codex', 'opencode', 'agent', 'qwen', 'gemini')
67    pub tool: String,
68    /// Working directory for the agent
69    pub working_directory: String,
70    /// Prompt for the agent
71    pub prompt: Option<String>,
72    /// File containing prompt input for stdin-based tools
73    pub prompt_file: Option<String>,
74    /// System prompt for the agent
75    pub system_prompt: Option<String>,
76    /// Append to the default system prompt (tool-specific)
77    pub append_system_prompt: Option<String>,
78    /// Model to use (tool-specific)
79    pub model: Option<String>,
80    /// Fallback model to use when the primary model is overloaded (tool-specific)
81    pub fallback_model: Option<String>,
82    /// Isolation mode: 'none', 'screen', 'docker'
83    pub isolation: String,
84    /// Screen session name (for screen isolation)
85    pub screen_name: Option<String>,
86    /// Container name (for docker isolation)
87    pub container_name: Option<String>,
88    /// Enable JSON output mode
89    pub json: bool,
90    /// Resume a previous session (tool-specific)
91    pub resume: Option<String>,
92    /// Enable verbose output (tool-specific)
93    pub verbose: bool,
94    /// Re-emit user messages in streaming output (tool-specific)
95    pub replay_user_messages: bool,
96    /// Use a specific session ID (tool-specific)
97    pub session_id: Option<String>,
98    /// Fork a resumed session into a new session (tool-specific)
99    pub fork_session: bool,
100    /// Enforce native read-only/planning mode
101    pub read_only: bool,
102    /// Enforce native planning mode (where the tool distinguishes it)
103    pub plan_only: bool,
104    /// Approve each mutating command (ask mode), relayed over the tool's native
105    /// per-command JSON permission protocol (only `claude` and `agent`)
106    pub approve_each: bool,
107    /// Override the tool executable path/name
108    pub executable: Option<String>,
109    /// Extra raw arguments appended after typed tool arguments
110    pub extra_args: Vec<String>,
111    /// Extra environment variables applied to the tool executable
112    pub extra_env: Vec<(String, String)>,
113    /// Do not add default autonomous safety bypass flags
114    pub skip_default_safety_flags: bool,
115}
116
117/// Agent result from stop()
118#[derive(Debug, Clone, Default)]
119pub struct AgentResult {
120    /// Exit code from the process
121    pub exit_code: i32,
122    /// Plain text output (stdout + stderr)
123    pub plain_output: String,
124    /// Parsed JSON messages (if tool supports it)
125    pub parsed_output: Option<Vec<Value>>,
126    /// Session ID for resuming
127    pub session_id: Option<String>,
128    /// Aggregated stream token usage, when the tool exposes it
129    pub usage: Option<Value>,
130    /// Stable normalized metadata for caller reporting
131    pub metadata: ResultMetadata,
132}
133
134/// Agent start options
135#[derive(Debug, Clone, Default)]
136pub struct AgentStartOptions {
137    /// If true, just show the command
138    pub dry_run: bool,
139    /// Run in detached mode
140    pub detached: bool,
141    /// Stream output to console
142    pub attached: bool,
143}
144
145/// Agent stop options
146#[derive(Debug, Clone, Default)]
147pub struct AgentStopOptions {
148    /// If true, just show the command
149    pub dry_run: bool,
150}
151
152/// Agent controller
153pub struct Agent {
154    options: AgentOptions,
155    process_handle: Option<ProcessHandle>,
156    output_stream: Option<JsonOutputStream>,
157    session_id: Option<String>,
158    prompt_temp_dir: Option<PathBuf>,
159}
160
161fn supports_prompt_file_input(tool: &str) -> bool {
162    matches!(
163        tool,
164        "claude" | "codex" | "opencode" | "agent" | "qwen" | "gemini"
165    )
166}
167
168fn build_prompt_file_content(
169    tool: &str,
170    prompt: Option<&str>,
171    system_prompt: Option<&str>,
172) -> String {
173    if tool == "claude" {
174        return prompt.unwrap_or_default().to_string();
175    }
176
177    match (system_prompt, prompt) {
178        (Some(system_prompt), Some(prompt)) => format!("{}\n\n{}", system_prompt, prompt),
179        (Some(system_prompt), None) => system_prompt.to_string(),
180        (None, Some(prompt)) => prompt.to_string(),
181        (None, None) => String::new(),
182    }
183}
184
185fn should_create_prompt_file(options: &AgentOptions, dry_run: bool) -> bool {
186    if dry_run || options.prompt_file.is_some() || !supports_prompt_file_input(&options.tool) {
187        return false;
188    }
189
190    if options.tool == "claude" {
191        return options.prompt.is_some();
192    }
193
194    options.prompt.is_some() || options.system_prompt.is_some()
195}
196
197fn extract_usage_value(tool: &str, output: &str) -> Option<Value> {
198    match tool {
199        "claude" => serde_json::to_value(tools::claude::extract_usage(output)).ok(),
200        "codex" => serde_json::to_value(tools::codex::extract_usage(output)).ok(),
201        "opencode" => serde_json::to_value(tools::opencode::extract_usage(output)).ok(),
202        "agent" => serde_json::to_value(tools::agent::extract_usage(output)).ok(),
203        "qwen" => serde_json::to_value(tools::qwen::extract_usage(output)).ok(),
204        "gemini" => serde_json::to_value(tools::gemini::extract_usage(output)).ok(),
205        _ => None,
206    }
207}
208
209impl Agent {
210    /// Create a new agent controller
211    ///
212    /// # Arguments
213    /// * `options` - Agent configuration
214    ///
215    /// # Returns
216    /// Result with Agent or error message
217    pub fn new(options: AgentOptions) -> Result<Self, String> {
218        // Validate required options
219        if options.tool.is_empty() {
220            return Err("tool is required".to_string());
221        }
222        if options.working_directory.is_empty() {
223            return Err("working_directory is required".to_string());
224        }
225        if options.isolation == "screen" && options.screen_name.is_none() {
226            return Err("screen_name is required for screen isolation".to_string());
227        }
228        if options.isolation == "docker" && options.container_name.is_none() {
229            return Err("container_name is required for docker isolation".to_string());
230        }
231        if (options.read_only || options.plan_only) && !supports_read_only(&options.tool) {
232            return Err(read_only_unsupported_error(&options.tool));
233        }
234        if options.approve_each && !supports_ask(&options.tool) {
235            return Err(ask_unsupported_error(&options.tool));
236        }
237
238        Ok(Self {
239            options,
240            process_handle: None,
241            output_stream: None,
242            session_id: None,
243            prompt_temp_dir: None,
244        })
245    }
246
247    async fn cleanup_prompt_temp_dir(&mut self) {
248        if let Some(dir) = self.prompt_temp_dir.take() {
249            let _ = tokio::fs::remove_dir_all(dir).await;
250        }
251    }
252
253    async fn prepare_prompt_file(&mut self, dry_run: bool) -> Result<Option<String>, String> {
254        if !should_create_prompt_file(&self.options, dry_run) {
255            return Ok(self.options.prompt_file.clone());
256        }
257
258        let unique_id = SystemTime::now()
259            .duration_since(UNIX_EPOCH)
260            .map_err(|e| e.to_string())?
261            .as_nanos();
262        let temp_dir = std::env::temp_dir().join(format!(
263            "agent-commander-{}-{}",
264            std::process::id(),
265            unique_id
266        ));
267        tokio::fs::create_dir(&temp_dir)
268            .await
269            .map_err(|e| e.to_string())?;
270        self.prompt_temp_dir = Some(temp_dir.clone());
271        let prompt_file = temp_dir.join("prompt.txt");
272        let content = build_prompt_file_content(
273            &self.options.tool,
274            self.options.prompt.as_deref(),
275            self.options.system_prompt.as_deref(),
276        );
277
278        let mut open_options = tokio::fs::OpenOptions::new();
279        open_options.write(true).create_new(true);
280        #[cfg(unix)]
281        {
282            open_options.mode(0o600);
283        }
284        let mut file = open_options
285            .open(&prompt_file)
286            .await
287            .map_err(|e| e.to_string())?;
288        file.write_all(content.as_bytes())
289            .await
290            .map_err(|e| e.to_string())?;
291
292        Ok(Some(prompt_file.to_string_lossy().into_owned()))
293    }
294
295    /// Start the agent (non-blocking)
296    ///
297    /// # Arguments
298    /// * `start_options` - Start options
299    ///
300    /// # Returns
301    /// Result indicating success or error
302    pub async fn start(&mut self, start_options: AgentStartOptions) -> Result<(), String> {
303        // Create output stream for JSON parsing if in JSON mode
304        if self.options.json {
305            self.output_stream = Some(create_output_stream());
306        }
307
308        let prepared_prompt_file = match self.prepare_prompt_file(start_options.dry_run).await {
309            Ok(prompt_file) => prompt_file,
310            Err(error) => {
311                self.cleanup_prompt_temp_dir().await;
312                return Err(error);
313            }
314        };
315        let prompt_handled_by_temp_file =
316            prepared_prompt_file.is_some() && self.options.prompt_file.is_none();
317
318        // Build the command
319        let command_options = AgentCommandOptions {
320            tool: self.options.tool.clone(),
321            working_directory: self.options.working_directory.clone(),
322            prompt: if prompt_handled_by_temp_file {
323                None
324            } else {
325                self.options.prompt.clone()
326            },
327            prompt_file: prepared_prompt_file,
328            system_prompt: if prompt_handled_by_temp_file && self.options.tool != "claude" {
329                None
330            } else {
331                self.options.system_prompt.clone()
332            },
333            append_system_prompt: self.options.append_system_prompt.clone(),
334            model: self.options.model.clone(),
335            fallback_model: self.options.fallback_model.clone(),
336            json: self.options.json,
337            verbose: self.options.verbose,
338            replay_user_messages: self.options.replay_user_messages,
339            resume: self.options.resume.clone(),
340            session_id: self.options.session_id.clone(),
341            fork_session: self.options.fork_session,
342            read_only: self.options.read_only,
343            plan_only: self.options.plan_only,
344            approve_each: self.options.approve_each,
345            executable: self.options.executable.clone(),
346            extra_args: self.options.extra_args.clone(),
347            extra_env: self.options.extra_env.clone(),
348            skip_default_safety_flags: self.options.skip_default_safety_flags,
349            isolation: self.options.isolation.clone(),
350            screen_name: self.options.screen_name.clone(),
351            container_name: self.options.container_name.clone(),
352            detached: start_options.detached,
353        };
354
355        let command = build_agent_command(&command_options);
356
357        if start_options.dry_run {
358            println!("Dry run - command that would be executed:");
359            println!("{}", command);
360            return Ok(());
361        }
362
363        if start_options.detached {
364            // For detached mode, use execute_detached
365            if let Err(error) = execute_detached(&command).await.map_err(|e| e.to_string()) {
366                self.cleanup_prompt_temp_dir().await;
367                return Err(error);
368            }
369            println!("Agent started in detached mode");
370            if self.options.isolation == "screen" {
371                if let Some(ref name) = self.options.screen_name {
372                    println!("Screen session: {}", name);
373                }
374            } else if self.options.isolation == "docker" {
375                if let Some(ref name) = self.options.container_name {
376                    println!("Container: {}", name);
377                }
378            }
379        } else {
380            // For attached mode, start command without waiting
381            let handle = match start_command(&command, start_options.attached)
382                .await
383                .map_err(|e| e.to_string())
384            {
385                Ok(handle) => handle,
386                Err(error) => {
387                    self.cleanup_prompt_temp_dir().await;
388                    return Err(error);
389                }
390            };
391            self.process_handle = Some(handle);
392        }
393
394        Ok(())
395    }
396
397    /// Stop the agent and collect output
398    ///
399    /// # Arguments
400    /// * `stop_options` - Stop options
401    ///
402    /// # Returns
403    /// Result with agent output or error
404    pub async fn stop(&mut self, stop_options: AgentStopOptions) -> Result<AgentResult, String> {
405        // For isolation modes, send stop command
406        if self.options.isolation == "screen" || self.options.isolation == "docker" {
407            let stop_command = if self.options.isolation == "screen" {
408                let screen_name = self
409                    .options
410                    .screen_name
411                    .as_ref()
412                    .ok_or("screen_name is required to stop screen session")?;
413                build_screen_stop_command(screen_name)
414            } else {
415                let container_name = self
416                    .options
417                    .container_name
418                    .as_ref()
419                    .ok_or("container_name is required to stop docker container")?;
420                build_docker_stop_command(container_name)
421            };
422
423            if stop_options.dry_run {
424                println!("Dry run - command that would be executed:");
425                println!("{}", stop_command);
426                return Ok(AgentResult {
427                    metadata: build_normalized_result_metadata(BuildMetadataOptions {
428                        tool: &self.options.tool,
429                        exit_code: 0,
430                        plain_output: "",
431                        parsed_output: None,
432                        session_id: None,
433                        usage: None,
434                    }),
435                    ..Default::default()
436                });
437            }
438
439            let result = match execute_command(&stop_command, false, true)
440                .await
441                .map_err(|e| e.to_string())
442            {
443                Ok(result) => result,
444                Err(error) => {
445                    self.cleanup_prompt_temp_dir().await;
446                    return Err(error);
447                }
448            };
449            self.cleanup_prompt_temp_dir().await;
450
451            let metadata = build_normalized_result_metadata(BuildMetadataOptions {
452                tool: &self.options.tool,
453                exit_code: result.exit_code,
454                plain_output: &result.stdout,
455                parsed_output: None,
456                session_id: None,
457                usage: None,
458            });
459
460            return Ok(AgentResult {
461                exit_code: result.exit_code,
462                plain_output: result.stdout,
463                parsed_output: None,
464                session_id: None,
465                usage: None,
466                metadata,
467            });
468        }
469
470        // For no isolation, wait for process to complete and collect output
471        if self.options.isolation == "none" || self.options.isolation.is_empty() {
472            if self.process_handle.is_none() {
473                self.cleanup_prompt_temp_dir().await;
474                return Err("Agent not started or already stopped".to_string());
475            }
476            let handle = self
477                .process_handle
478                .as_mut()
479                .ok_or("Agent not started or already stopped")?;
480
481            // Wait for the process to exit
482            let exit_code = match handle.wait_for_exit().await.map_err(|e| e.to_string()) {
483                Ok(exit_code) => exit_code,
484                Err(error) => {
485                    self.cleanup_prompt_temp_dir().await;
486                    return Err(error);
487                }
488            };
489
490            let (stdout, stderr, _) = handle.get_output();
491
492            // Combine stdout and stderr for plain output
493            let plain_output = if stderr.is_empty() {
494                stdout.to_string()
495            } else {
496                format!("{}\n{}", stdout, stderr)
497            };
498
499            // Process output through stream if available
500            let mut parsed_output = None;
501            if let Some(ref mut stream) = self.output_stream {
502                stream.process(stdout);
503                stream.flush();
504                let messages = stream.get_messages();
505                if !messages.is_empty() {
506                    parsed_output = Some(messages.to_vec());
507                }
508            }
509
510            if parsed_output.is_none() {
511                parsed_output = Some(if self.options.tool == "gemini" {
512                    tools::gemini::parse_output(stdout)
513                } else {
514                    streaming::parse_ndjson(stdout)
515                });
516            }
517
518            // Try to extract session ID
519            if is_tool_supported(&self.options.tool) {
520                match self.options.tool.as_str() {
521                    "claude" => {
522                        self.session_id = tools::claude::extract_session_id(stdout);
523                    }
524                    "codex" => {
525                        self.session_id = tools::codex::extract_session_id(stdout);
526                    }
527                    "opencode" => {
528                        self.session_id = tools::opencode::extract_session_id(stdout);
529                    }
530                    "agent" => {
531                        self.session_id = tools::agent::extract_session_id(stdout);
532                    }
533                    "qwen" => self.session_id = tools::qwen::extract_session_id(stdout),
534                    "gemini" => self.session_id = tools::gemini::extract_session_id(stdout),
535                    _ => {}
536                }
537            }
538
539            let usage = extract_usage_value(&self.options.tool, stdout);
540            let mut metadata = build_normalized_result_metadata(BuildMetadataOptions {
541                tool: &self.options.tool,
542                exit_code,
543                plain_output: &plain_output,
544                parsed_output: parsed_output.as_deref(),
545                session_id: self.session_id.clone(),
546                usage: usage.clone(),
547            });
548            if (self.options.json || self.options.tool == "agent")
549                && is_tool_supported(&self.options.tool)
550            {
551                completion::require_completed_result(
552                    &mut metadata,
553                    &self.options.tool,
554                    parsed_output.as_deref().unwrap_or_default(),
555                );
556            }
557
558            let result = AgentResult {
559                exit_code,
560                plain_output,
561                parsed_output,
562                session_id: self.session_id.clone(),
563                usage,
564                metadata,
565            };
566            self.cleanup_prompt_temp_dir().await;
567            return Ok(result);
568        }
569
570        Err(format!(
571            "Unsupported isolation mode: {}",
572            self.options.isolation
573        ))
574    }
575
576    /// Cancel a running process and collect its final output and metadata.
577    pub async fn cancel(&mut self) -> Result<AgentResult, String> {
578        if self.options.isolation == "none" || self.options.isolation.is_empty() {
579            if let Some(handle) = self.process_handle.as_mut() {
580                handle
581                    .terminate()
582                    .await
583                    .map_err(|error| error.to_string())?;
584            }
585        }
586        self.stop(AgentStopOptions::default()).await
587    }
588
589    /// Get the current session ID (if available)
590    pub fn get_session_id(&self) -> Option<&String> {
591        self.session_id.as_ref()
592    }
593
594    /// Get all collected messages from the output stream
595    pub fn get_messages(&self) -> Vec<&Value> {
596        if let Some(ref stream) = self.output_stream {
597            stream.get_messages().iter().collect()
598        } else {
599            Vec::new()
600        }
601    }
602}
603
604/// Create an agent controller (convenience function)
605///
606/// # Arguments
607/// * `options` - Agent configuration
608///
609/// # Returns
610/// Result with Agent or error message
611pub fn agent(options: AgentOptions) -> Result<Agent, String> {
612    Agent::new(options)
613}
614
615// Tests are in rust/tests/lib_tests.rs