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 api_status;
13pub mod background_tasks;
14pub mod claude_transcript;
15pub mod cli_parser;
16pub mod codex_rollout;
17pub mod command_builder;
18mod completion;
19pub mod context_usage;
20pub mod error_text;
21pub mod executor;
22pub mod file_tail;
23pub mod live_input;
24pub mod permissions;
25pub mod result_close;
26pub mod result_metadata;
27pub mod streaming;
28pub mod structured_output;
29pub mod tool_overrides;
30pub mod tool_version;
31pub mod tools;
32pub mod tui;
33pub mod usage_limit;
34pub mod usage_windows;
35
36use serde_json::Value;
37use std::path::{Path, PathBuf};
38use std::sync::atomic::{AtomicU64, Ordering};
39use std::time::{SystemTime, UNIX_EPOCH};
40use tokio::io::AsyncWriteExt;
41
42pub use cli_parser::{
43    parse_args, parse_start_agent_args, parse_stop_agent_args, show_start_agent_help,
44    show_stop_agent_help, validate_start_agent_options, validate_stop_agent_options,
45    StartAgentOptions, StopAgentOptions, ValidationResult,
46};
47
48pub use command_builder::{
49    build_agent_command, build_base_command, build_docker_stop_command, build_piped_command,
50    build_screen_stop_command, read_only_unsupported_error, supports_read_only,
51    AgentCommandOptions,
52};
53
54pub use permissions::{
55    ask_scope, ask_unsupported_error, build_permission_response, normalize_permission_request,
56    permission_parity, supports_ask, NormalizedPermissionRequest, PermissionParityRow,
57    PermissionRelay, ASK_DECISIONS, ASK_SUPPORTED_TOOLS,
58};
59
60pub use tools::shell::{
61    build_child_environment, build_child_environment_passing, file_content_arg, InheritEnv,
62};
63
64pub use executor::{
65    execute_command, execute_detached, execute_detached_with_env, is_process_group_alive,
66    normalize_exit, setup_signal_handler, signal_from_exit_code, signal_name, start_command,
67    start_command_with_env, start_command_with_stdin, ExecutionResult, ProcessHandle,
68    DEFAULT_KILL_AFTER, DEFAULT_PIPE_DRAIN,
69};
70
71pub use api_status::*;
72
73pub use background_tasks::{
74    assess_background_tasks, extract_observed_models, is_real_model_id, print_wait_ceiling_seconds,
75    track_background_tasks, BackgroundTask, BackgroundTaskAssessment, BackgroundTaskState,
76    StoppedBackgroundTask, PRINT_BG_CEILING_PATTERN,
77};
78
79pub use result_close::{
80    has_final_result, wait_for_exit_after_result, watch_process_exit, ResultCloseOptions,
81    ResultCloseOutcome, StdoutMessageReader, DEFAULT_RESULT_POLL,
82};
83
84pub use codex_rollout::{
85    apply_codex_rollout_context_usage, apply_codex_rollout_usage_limit,
86    apply_codex_rollout_usage_windows, can_resume_codex_session,
87    classify_codex_rate_limit_snapshot, codex_rollout_context_usage, codex_rollout_limit_facts,
88    codex_sessions_dir, detect_codex_rollout_usage_limit, find_codex_rollout_file,
89    is_codex_rollout_file_name, read_codex_rollout_limit_facts, CodexLimitVerdict,
90    CodexRolloutLimitFacts, CodexRolloutOptions, CODEX_ROLLOUT_LIMIT_SOURCE,
91    CODEX_SESSIONS_DIRNAME, ROLLOUT_TAIL_BYTES,
92};
93
94pub use claude_transcript::{
95    apply_claude_transcript_usage_limit, claude_project_slugs, claude_transcript_api_error,
96    claude_transcript_candidates, read_claude_transcript_api_error, ClaudeTranscriptApiError,
97    ClaudeTranscriptOptions, CLAUDE_TRANSCRIPT_LIMIT_SOURCE, TRANSCRIPT_TAIL_BYTES,
98};
99
100pub use context_usage::{
101    claude_request_context_tokens, context_reading_from_message, extract_context_usage,
102    ContextReading, ContextUsage,
103};
104pub use file_tail::read_file_tail;
105pub use live_input::{
106    build_interrupt_frame, build_user_input_frame, live_input_unsupported_error,
107    supports_live_input,
108};
109
110pub use result_metadata::{
111    build_normalized_result_metadata, BuildMetadataOptions, PricingInfo, ResultMetadata,
112};
113
114pub use error_text::{first_error_text, stringify_error_value, MAX_ERROR_TEXT_LENGTH};
115
116pub use usage_limit::{
117    classify_debug_lines, classify_rate_limit_event, detect_usage_limit_sources,
118    extract_reset_time, extract_timezone, format_epoch_reset_time_utc, is_recoverable_tool_error,
119    is_usage_limit_text, limit_scan_text, DebugLines, UsageLimitVerdict,
120};
121
122pub use structured_output::extract_structured_output;
123
124pub use streaming::{
125    create_input_stream, create_output_stream, parse_json_records, parse_ndjson, parse_ndjson_line,
126    stringify_ndjson, stringify_ndjson_line, JsonInputStream, JsonOutputStream, JsonRecordEvent,
127    JsonRecordScanner, ParseError,
128};
129
130pub use tools::{
131    get_tool, is_tool_supported, list_tools, AgentTool, ClaudeTool, CodexTool, OpencodeTool, Tool,
132    ToolRegistry,
133};
134
135pub use usage_windows::{
136    claude_rate_limit_windows, codex_rate_limit_windows, extract_usage_windows,
137    merge_usage_windows, usage_windows_from_message, UsageWindow, USAGE_WINDOW_KINDS,
138};
139
140/// Shell quoting for `ToolOverrides::build_command` implementations
141pub use tools::shell::escape_arg;
142
143pub use tool_overrides::{
144    BuildCommandFn, ExtractSessionIdFn, ExtractUsageFn, ParseOutputFn, ToolOverrides,
145};
146
147pub use tool_version::{
148    build_version_command, compare_versions, get_tool_version, parse_tool_version,
149    tool_version_from_output, ToolVersion,
150};
151
152pub use tools::launch_options::{
153    check_gateway_token, check_launch_options_against, check_launch_options_supported,
154    claude_gateway_settings, codex_gateway_overrides, codex_mcp_servers_override, json_schema_arg,
155    launch_capabilities, normalize_gateway, normalize_reasoning_effort, push_attachments,
156    push_directories, resolve_gateway, to_toml_value, GatewayOptions, LaunchCapabilities,
157    LaunchOptions, CLAUDE_GATEWAY_UNSET_ENV, CLAUDE_REASONING_EFFORTS, CODEX_GATEWAY_PROVIDER_ID,
158    CODEX_REASONING_EFFORTS, ROUTER_SERVICE_PATHS,
159};
160
161/// Agent options for creating a controller
162#[derive(Debug, Clone, Default)]
163pub struct AgentOptions {
164    /// CLI tool to use (e.g., 'claude', 'codex', 'opencode', 'agent', 'qwen', 'gemini')
165    pub tool: String,
166    /// Working directory for the agent
167    pub working_directory: String,
168    /// Prompt for the agent
169    pub prompt: Option<String>,
170    /// File containing prompt input for stdin-based tools
171    pub prompt_file: Option<String>,
172    /// System prompt for the agent
173    pub system_prompt: Option<String>,
174    /// Append to the default system prompt (tool-specific)
175    pub append_system_prompt: Option<String>,
176    /// Model to use (tool-specific)
177    pub model: Option<String>,
178    /// Fallback model to use when the primary model is overloaded (tool-specific)
179    pub fallback_model: Option<String>,
180    /// Isolation mode: 'none', 'screen', 'docker'
181    pub isolation: String,
182    /// Screen session name (for screen isolation)
183    pub screen_name: Option<String>,
184    /// Container name (for docker isolation)
185    pub container_name: Option<String>,
186    /// Enable JSON output mode
187    pub json: bool,
188    /// Resume a previous session (tool-specific)
189    pub resume: Option<String>,
190    /// Enable verbose output (tool-specific)
191    pub verbose: bool,
192    /// Re-emit user messages in streaming output (tool-specific)
193    pub replay_user_messages: bool,
194    /// Use a specific session ID (tool-specific)
195    pub session_id: Option<String>,
196    /// Fork a resumed session into a new session (tool-specific)
197    pub fork_session: bool,
198    /// Enforce native read-only/planning mode
199    pub read_only: bool,
200    /// Enforce native planning mode (where the tool distinguishes it)
201    pub plan_only: bool,
202    /// Approve each mutating command (ask mode), relayed over the tool's native
203    /// per-command JSON permission protocol (only `claude` and `agent`)
204    pub approve_each: bool,
205    /// Override the tool executable path/name
206    pub executable: Option<String>,
207    /// Extra raw arguments appended after typed tool arguments
208    pub extra_args: Vec<String>,
209    /// Extra environment variables applied to the tool executable
210    pub extra_env: Vec<(String, String)>,
211    /// Variables removed from the inherited environment of the tool
212    pub unset_env: Vec<String>,
213    /// Which host variables the tool inherits: all (default), none, or an
214    /// allowlist (issue #60)
215    pub inherit_env: InheritEnv,
216    /// Explicit environment replacing the inherited one; `extra_env` and
217    /// `unset_env` still apply on top (issue #60)
218    pub env: Option<Vec<(String, String)>>,
219    /// Do not add default autonomous safety bypass flags
220    pub skip_default_safety_flags: bool,
221    /// Shared launch options: generation controls, reasoning effort, MCP servers, strict MCP
222    /// configuration, extra workspace directories, attachments and a JSON
223    /// Schema for structured output
224    pub launch: LaunchOptions,
225    /// Keep stdin open for [`Agent::send_message`] and [`Agent::interrupt`]
226    /// (`claude`, `qwen`, `agent`; attached runs without isolation). The
227    /// prompt becomes the first stream-json frame and JSON output is forced.
228    pub live_input: bool,
229    /// Stop on a Claude 401/403 `api_retry` as `auth_refused` (#69); `None`: on with a gateway
230    pub fail_fast_on_auth_error: Option<bool>,
231    /// Replace the command builder, output parser, session ID or usage
232    /// extractor, or launch capabilities for this run
233    pub tool_overrides: ToolOverrides,
234}
235
236/// Agent result from stop()
237#[derive(Debug, Clone, Default)]
238pub struct AgentResult {
239    /// Exit code from the process
240    pub exit_code: i32,
241    /// Plain text output (stdout + stderr)
242    pub plain_output: String,
243    /// Parsed JSON messages (if tool supports it)
244    pub parsed_output: Option<Vec<Value>>,
245    /// Session ID for resuming
246    pub session_id: Option<String>,
247    /// Aggregated stream token usage, when the tool exposes it
248    pub usage: Option<Value>,
249    /// Stable normalized metadata for caller reporting
250    pub metadata: ResultMetadata,
251}
252
253/// Agent start options
254#[derive(Debug, Clone, Default)]
255pub struct AgentStartOptions {
256    /// If true, just show the command
257    pub dry_run: bool,
258    /// Run in detached mode
259    pub detached: bool,
260    /// Stream output to console
261    pub attached: bool,
262}
263
264/// Agent stop options
265#[derive(Debug, Clone, Default)]
266pub struct AgentStopOptions {
267    /// If true, just show the command
268    pub dry_run: bool,
269    /// Stop a process that stays this long after its final result once no
270    /// background task runs (hive-mind#1280); `None` waits for it to exit
271    pub close_timeout: Option<std::time::Duration>,
272    /// Extra time a process may stay after its result while background tasks
273    /// run; `None` leaves them to the tool's own ceiling
274    pub background_wait: Option<std::time::Duration>,
275    /// The caller already stopped the process after its final result
276    pub terminated_after_result: bool,
277}
278
279/// Agent controller
280pub struct Agent {
281    options: AgentOptions,
282    process_handle: Option<ProcessHandle>,
283    output_stream: Option<JsonOutputStream>,
284    session_id: Option<String>,
285    prompt_temp_dir: Option<PathBuf>,
286}
287
288fn supports_prompt_file_input(tool: &str) -> bool {
289    matches!(
290        tool,
291        "claude" | "codex" | "opencode" | "agent" | "qwen" | "gemini"
292    )
293}
294
295fn build_prompt_file_content(
296    tool: &str,
297    prompt: Option<&str>,
298    system_prompt: Option<&str>,
299) -> String {
300    if tool == "claude" {
301        return prompt.unwrap_or_default().to_string();
302    }
303
304    match (system_prompt, prompt) {
305        (Some(system_prompt), Some(prompt)) => format!("{}\n\n{}", system_prompt, prompt),
306        (Some(system_prompt), None) => system_prompt.to_string(),
307        (None, Some(prompt)) => prompt.to_string(),
308        (None, None) => String::new(),
309    }
310}
311
312/// Names of prompt directories created by this process
313static PROMPT_DIR_SEQUENCE: AtomicU64 = AtomicU64::new(0);
314
315/// Names tried before a prompt directory is given up
316const PROMPT_DIR_ATTEMPTS: usize = 16;
317
318/// Create a new directory for a prompt file under `parent`.
319///
320/// The name holds the pid, the clock and a per-process sequence, because
321/// controllers started in parallel can read the same clock tick (macOS clocks
322/// are coarse). A name that already exists, such as a leftover from a reused
323/// pid, is skipped.
324async fn create_prompt_temp_dir(parent: &Path, nanos: u128) -> Result<PathBuf, String> {
325    for _ in 0..PROMPT_DIR_ATTEMPTS {
326        let sequence = PROMPT_DIR_SEQUENCE.fetch_add(1, Ordering::Relaxed);
327        let dir = parent.join(format!(
328            "agent-commander-{}-{nanos}-{sequence}",
329            std::process::id()
330        ));
331        match tokio::fs::create_dir(&dir).await {
332            Ok(()) => return Ok(dir),
333            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
334            Err(error) => return Err(error.to_string()),
335        }
336    }
337    Err(format!(
338        "could not create a prompt directory in {}",
339        parent.display()
340    ))
341}
342
343/// Write a new, owner-only prompt file and return once all of it is on disk.
344async fn write_prompt_file(path: &Path, content: &str) -> Result<(), String> {
345    let mut open_options = tokio::fs::OpenOptions::new();
346    open_options.write(true).create_new(true);
347    #[cfg(unix)]
348    {
349        open_options.mode(0o600);
350    }
351    let mut file = open_options.open(path).await.map_err(|e| e.to_string())?;
352    file.write_all(content.as_bytes())
353        .await
354        .map_err(|e| e.to_string())?;
355    // tokio writes at most 2 MiB per background operation and `write_all`
356    // returns once the last one is queued; `flush` waits for it to finish.
357    file.flush().await.map_err(|e| e.to_string())
358}
359
360fn should_create_prompt_file(options: &AgentOptions, dry_run: bool) -> bool {
361    if dry_run || options.prompt_file.is_some() || !supports_prompt_file_input(&options.tool) {
362        return false;
363    }
364
365    if options.tool == "claude" {
366        return options.prompt.is_some();
367    }
368
369    options.prompt.is_some() || options.system_prompt.is_some()
370}
371
372fn extract_usage_value(tool: &str, output: &str) -> Option<Value> {
373    match tool {
374        "claude" => serde_json::to_value(tools::claude::extract_usage(output)).ok(),
375        "codex" => serde_json::to_value(tools::codex::extract_usage(output)).ok(),
376        "opencode" => serde_json::to_value(tools::opencode::extract_usage(output)).ok(),
377        "agent" => serde_json::to_value(tools::agent::extract_usage(output)).ok(),
378        "qwen" => serde_json::to_value(tools::qwen::extract_usage(output)).ok(),
379        "gemini" => serde_json::to_value(tools::gemini::extract_usage(output)).ok(),
380        _ => None,
381    }
382}
383
384impl Agent {
385    /// Create a new agent controller
386    ///
387    /// # Arguments
388    /// * `options` - Agent configuration
389    ///
390    /// # Returns
391    /// Result with Agent or error message
392    pub fn new(options: AgentOptions) -> Result<Self, String> {
393        // Validate required options
394        if options.tool.is_empty() {
395            return Err("tool is required".to_string());
396        }
397        if options.working_directory.is_empty() {
398            return Err("working_directory is required".to_string());
399        }
400        if options.isolation == "screen" && options.screen_name.is_none() {
401            return Err("screen_name is required for screen isolation".to_string());
402        }
403        if options.isolation == "docker" && options.container_name.is_none() {
404            return Err("container_name is required for docker isolation".to_string());
405        }
406        if (options.read_only || options.plan_only) && !supports_read_only(&options.tool) {
407            return Err(read_only_unsupported_error(&options.tool));
408        }
409        if options.approve_each && !supports_ask(&options.tool) {
410            return Err(ask_unsupported_error(&options.tool));
411        }
412
413        Ok(Self {
414            options,
415            process_handle: None,
416            output_stream: None,
417            session_id: None,
418            prompt_temp_dir: None,
419        })
420    }
421
422    async fn cleanup_prompt_temp_dir(&mut self) {
423        if let Some(dir) = self.prompt_temp_dir.take() {
424            let _ = tokio::fs::remove_dir_all(dir).await;
425        }
426    }
427
428    /// The tool's environment: `extra_env` values travel through `spawn`,
429    /// never through the command line (issue #60). The gateway token
430    /// variable is always inherited (issue #65).
431    fn child_environment(&self) -> Result<Vec<(String, String)>, String> {
432        let pass_env: Vec<String> = self
433            .options
434            .launch
435            .gateway
436            .iter()
437            .map(|gateway| gateway.token_env.clone())
438            .collect();
439        build_child_environment_passing(
440            std::env::vars(),
441            &self.options.inherit_env,
442            self.options.env.as_deref(),
443            &pass_env,
444            &self.options.unset_env,
445            &self.options.extra_env,
446        )
447    }
448
449    async fn ensure_prompt_temp_dir(&mut self) -> Result<PathBuf, String> {
450        if let Some(dir) = &self.prompt_temp_dir {
451            return Ok(dir.clone());
452        }
453        let nanos = SystemTime::now()
454            .duration_since(UNIX_EPOCH)
455            .map_err(|e| e.to_string())?
456            .as_nanos();
457        let dir = create_prompt_temp_dir(&std::env::temp_dir(), nanos).await?;
458        self.prompt_temp_dir = Some(dir.clone());
459        Ok(dir)
460    }
461
462    /// Write system prompts and the JSON Schema to owner-only files so they
463    /// stay out of `ps` / `/proc/<pid>/cmdline` and argv limits (issue #60).
464    async fn move_inline_values_to_files(
465        &mut self,
466        options: &mut AgentCommandOptions,
467    ) -> Result<(), String> {
468        let claude = options.tool == "claude";
469        let schema_tool = matches!(options.tool.as_str(), "claude" | "codex" | "qwen");
470        let mut files: Vec<(&str, String)> = Vec::new();
471        if claude {
472            if let Some(text) = options.system_prompt.clone().filter(|t| !t.is_empty()) {
473                files.push(("system-prompt.txt", text));
474            }
475            if let Some(text) = options
476                .append_system_prompt
477                .clone()
478                .filter(|t| !t.is_empty())
479            {
480                files.push(("append-system-prompt.txt", text));
481            }
482        }
483        if schema_tool {
484            if let Some(schema) = options.launch.json_schema.clone() {
485                files.push(("schema.json", json_schema_arg(&schema)));
486            }
487        }
488        if files.is_empty() {
489            return Ok(());
490        }
491        let dir = self.ensure_prompt_temp_dir().await?;
492        for (name, content) in files {
493            let path = dir.join(name);
494            write_prompt_file(&path, &content).await?;
495            let path = path.to_string_lossy().into_owned();
496            match name {
497                "system-prompt.txt" => options.launch.system_prompt_file = Some(path),
498                "append-system-prompt.txt" => {
499                    options.launch.append_system_prompt_file = Some(path);
500                }
501                _ => options.launch.json_schema_file = Some(path),
502            }
503        }
504        Ok(())
505    }
506
507    async fn prepare_prompt_file(&mut self, dry_run: bool) -> Result<Option<String>, String> {
508        if !should_create_prompt_file(&self.options, dry_run) {
509            return Ok(self.options.prompt_file.clone());
510        }
511
512        let temp_dir = self.ensure_prompt_temp_dir().await?;
513        let prompt_file = temp_dir.join("prompt.txt");
514        let content = build_prompt_file_content(
515            &self.options.tool,
516            self.options.prompt.as_deref(),
517            self.options.system_prompt.as_deref(),
518        );
519
520        write_prompt_file(&prompt_file, &content).await?;
521
522        Ok(Some(prompt_file.to_string_lossy().into_owned()))
523    }
524
525    /// Start the agent (non-blocking)
526    ///
527    /// # Arguments
528    /// * `start_options` - Start options
529    ///
530    /// # Returns
531    /// Result indicating success or error
532    pub async fn start(&mut self, start_options: AgentStartOptions) -> Result<(), String> {
533        // Reject launch options the tool cannot honor before any side effects.
534        let capabilities = self
535            .options
536            .tool_overrides
537            .launch_capabilities
538            .unwrap_or_else(|| launch_capabilities(&self.options.tool));
539        check_launch_options_against(&self.options.tool, &self.options.launch, &capabilities)?;
540        let live = self.options.live_input;
541        if live && !supports_live_input(&self.options.tool) {
542            return Err(live_input_unsupported_error(&self.options.tool));
543        }
544        let isolated = !(self.options.isolation == "none" || self.options.isolation.is_empty());
545        if live && !start_options.dry_run && (start_options.detached || isolated) {
546            return Err(
547                "live_input needs an attached run without isolation (stdin is piped to the tool)."
548                    .to_string(),
549            );
550        }
551
552        // Fail on an invalid environment before any side effects (issue #60).
553        let child_env = self.child_environment()?;
554        if !start_options.dry_run {
555            check_gateway_token(self.options.launch.gateway.as_ref(), &child_env)?;
556        }
557
558        // Create output stream for JSON parsing if in JSON mode
559        if self.options.json || live {
560            self.output_stream = Some(create_output_stream());
561        }
562
563        // Live input writes the prompt as the first stdin frame instead.
564        let prepared_prompt_file = match self
565            .prepare_prompt_file(start_options.dry_run || live)
566            .await
567        {
568            Ok(prompt_file) => prompt_file,
569            Err(error) => {
570                self.cleanup_prompt_temp_dir().await;
571                return Err(error);
572            }
573        };
574        let prompt_handled_by_temp_file =
575            prepared_prompt_file.is_some() && self.options.prompt_file.is_none();
576
577        // Build the command
578        let command_options = AgentCommandOptions {
579            tool: self.options.tool.clone(),
580            working_directory: self.options.working_directory.clone(),
581            prompt: if prompt_handled_by_temp_file || live {
582                None
583            } else {
584                self.options.prompt.clone()
585            },
586            prompt_file: prepared_prompt_file,
587            system_prompt: if prompt_handled_by_temp_file && self.options.tool != "claude" {
588                None
589            } else {
590                self.options.system_prompt.clone()
591            },
592            append_system_prompt: self.options.append_system_prompt.clone(),
593            model: self.options.model.clone(),
594            fallback_model: self.options.fallback_model.clone(),
595            json: self.options.json || live,
596            verbose: self.options.verbose,
597            replay_user_messages: self.options.replay_user_messages,
598            resume: self.options.resume.clone(),
599            session_id: self.options.session_id.clone(),
600            fork_session: self.options.fork_session,
601            read_only: self.options.read_only,
602            plan_only: self.options.plan_only,
603            approve_each: self.options.approve_each,
604            stream_input: live,
605            executable: self.options.executable.clone(),
606            extra_args: self.options.extra_args.clone(),
607            extra_env: self.options.extra_env.clone(),
608            unset_env: self.options.unset_env.clone(),
609            skip_default_safety_flags: self.options.skip_default_safety_flags,
610            isolation: self.options.isolation.clone(),
611            screen_name: self.options.screen_name.clone(),
612            container_name: self.options.container_name.clone(),
613            detached: start_options.detached,
614            launch: self.options.launch.clone(),
615            overrides: self.options.tool_overrides.clone(),
616        };
617
618        let mut command_options = command_options;
619        if !start_options.dry_run && self.options.tool_overrides.build_command.is_none() {
620            if let Err(error) = self.move_inline_values_to_files(&mut command_options).await {
621                self.cleanup_prompt_temp_dir().await;
622                return Err(error);
623            }
624        }
625        let command = build_agent_command(&command_options);
626
627        if start_options.dry_run {
628            println!("Dry run - command that would be executed:");
629            println!("{}", command);
630            return Ok(());
631        }
632
633        if start_options.detached {
634            // For detached mode, use execute_detached
635            if let Err(error) = execute_detached_with_env(&command, Some(&child_env))
636                .await
637                .map_err(|e| e.to_string())
638            {
639                self.cleanup_prompt_temp_dir().await;
640                return Err(error);
641            }
642            println!("Agent started in detached mode");
643            if self.options.isolation == "screen" {
644                if let Some(ref name) = self.options.screen_name {
645                    println!("Screen session: {}", name);
646                }
647            } else if self.options.isolation == "docker" {
648                if let Some(ref name) = self.options.container_name {
649                    println!("Container: {}", name);
650                }
651            }
652        } else {
653            // For attached mode, start command without waiting
654            let started = if live {
655                start_command_with_env(&command, start_options.attached, true, &child_env).await
656            } else {
657                start_command_with_env(&command, start_options.attached, false, &child_env).await
658            };
659            let handle = match started.map_err(|e| e.to_string()) {
660                Ok(handle) => handle,
661                Err(error) => {
662                    self.cleanup_prompt_temp_dir().await;
663                    return Err(error);
664                }
665            };
666            self.process_handle = Some(handle);
667            if live {
668                // Kick off the turn by sending the user prompt as the first frame.
669                let prompt = self.options.prompt.clone().map_or(Value::Null, Value::from);
670                let frame = build_user_input_frame(
671                    &self.options.tool,
672                    &prompt,
673                    self.options.system_prompt.as_deref(),
674                )?;
675                self.write_input_frame(&frame).await?;
676            }
677        }
678
679        Ok(())
680    }
681
682    /// Stop the agent and collect output
683    ///
684    /// # Arguments
685    /// * `stop_options` - Stop options
686    ///
687    /// # Returns
688    /// Result with agent output or error
689    pub async fn stop(&mut self, stop_options: AgentStopOptions) -> Result<AgentResult, String> {
690        // For isolation modes, send stop command
691        if self.options.isolation == "screen" || self.options.isolation == "docker" {
692            let stop_command = if self.options.isolation == "screen" {
693                let screen_name = self
694                    .options
695                    .screen_name
696                    .as_ref()
697                    .ok_or("screen_name is required to stop screen session")?;
698                build_screen_stop_command(screen_name)
699            } else {
700                let container_name = self
701                    .options
702                    .container_name
703                    .as_ref()
704                    .ok_or("container_name is required to stop docker container")?;
705                build_docker_stop_command(container_name)
706            };
707
708            if stop_options.dry_run {
709                println!("Dry run - command that would be executed:");
710                println!("{}", stop_command);
711                return Ok(AgentResult {
712                    metadata: build_normalized_result_metadata(BuildMetadataOptions {
713                        tool: &self.options.tool,
714                        exit_code: 0,
715                        plain_output: "",
716                        parsed_output: None,
717                        session_id: None,
718                        usage: None,
719                        ..Default::default()
720                    }),
721                    ..Default::default()
722                });
723            }
724
725            let result = match execute_command(&stop_command, false, true)
726                .await
727                .map_err(|e| e.to_string())
728            {
729                Ok(result) => result,
730                Err(error) => {
731                    self.cleanup_prompt_temp_dir().await;
732                    return Err(error);
733                }
734            };
735            self.cleanup_prompt_temp_dir().await;
736
737            let metadata = build_normalized_result_metadata(BuildMetadataOptions {
738                tool: &self.options.tool,
739                exit_code: result.exit_code,
740                plain_output: &result.stdout,
741                parsed_output: None,
742                session_id: None,
743                usage: None,
744                signal: result.signal.clone(),
745                ..Default::default()
746            });
747
748            return Ok(AgentResult {
749                exit_code: result.exit_code,
750                plain_output: result.stdout,
751                parsed_output: None,
752                session_id: None,
753                usage: None,
754                metadata,
755            });
756        }
757
758        // For no isolation, wait for process to complete and collect output
759        if self.options.isolation == "none" || self.options.isolation.is_empty() {
760            if self.process_handle.is_none() {
761                self.cleanup_prompt_temp_dir().await;
762                return Err("Agent not started or already stopped".to_string());
763            }
764            let handle = self
765                .process_handle
766                .as_mut()
767                .ok_or("Agent not started or already stopped")?;
768            // End live input: the tool finishes the queued input and exits.
769            handle.end_stdin();
770
771            // Wait for the process to exit, closing it when it outlives its result
772            let gateway = self.options.launch.gateway.is_some();
773            let close = ResultCloseOptions {
774                close_timeout: stop_options.close_timeout,
775                background_wait: stop_options.background_wait,
776                fail_fast_on_auth_error: self.options.fail_fast_on_auth_error.unwrap_or(gateway),
777                ..Default::default()
778            };
779            let outcome = match watch_process_exit(handle, &self.options.tool, close).await {
780                Ok(outcome) => outcome,
781                Err(error) => {
782                    self.cleanup_prompt_temp_dir().await;
783                    return Err(error.to_string());
784                }
785            };
786            let exit_code = outcome.exit_code;
787            let terminated_after_result =
788                outcome.terminated_after_result || stop_options.terminated_after_result;
789
790            let (stdout, stderr, _) = handle.get_output();
791
792            // Combine stdout and stderr for plain output
793            let plain_output = if stderr.is_empty() {
794                stdout.to_string()
795            } else {
796                format!("{}\n{}", stdout, stderr)
797            };
798
799            // Process output through stream if available
800            // A caller's parser replaces the streamed messages too.
801            let overrides = &self.options.tool_overrides;
802            let mut parsed_output = overrides.parse_output.as_ref().map(|parse| parse(stdout));
803            if let (None, Some(stream)) = (&parsed_output, self.output_stream.as_mut()) {
804                stream.process(stdout);
805                stream.flush();
806                let messages = stream.get_messages();
807                if !messages.is_empty() {
808                    parsed_output = Some(messages.to_vec());
809                }
810            }
811
812            if parsed_output.is_none() {
813                parsed_output = Some(if self.options.tool == "gemini" {
814                    tools::gemini::parse_output(stdout)
815                } else {
816                    streaming::parse_json_records(stdout)
817                });
818            }
819
820            // Try to extract session ID
821            if let Some(extract) = &overrides.extract_session_id {
822                self.session_id = extract(stdout);
823            } else if is_tool_supported(&self.options.tool) {
824                match self.options.tool.as_str() {
825                    "claude" => {
826                        self.session_id = tools::claude::extract_session_id(stdout);
827                    }
828                    "codex" => {
829                        self.session_id = tools::codex::extract_session_id(stdout);
830                    }
831                    "opencode" => {
832                        self.session_id = tools::opencode::extract_session_id(stdout);
833                    }
834                    "agent" => {
835                        self.session_id = tools::agent::extract_session_id(stdout);
836                    }
837                    "qwen" => self.session_id = tools::qwen::extract_session_id(stdout),
838                    "gemini" => self.session_id = tools::gemini::extract_session_id(stdout),
839                    _ => {}
840                }
841            }
842
843            let usage = match &overrides.extract_usage {
844                Some(extract) => extract(stdout),
845                None => extract_usage_value(&self.options.tool, stdout),
846            };
847            let mut metadata = build_normalized_result_metadata(BuildMetadataOptions {
848                tool: &self.options.tool,
849                exit_code,
850                plain_output: &plain_output,
851                parsed_output: parsed_output.as_deref(),
852                session_id: self.session_id.clone(),
853                usage: usage.clone(),
854                signal: handle.signal().map(String::from),
855                terminated_after_result,
856                structured_output_requested: self.options.launch.json_schema.is_some(),
857                auth_refusal: outcome.auth_refusal,
858            });
859            // Codex and Claude can leave a usage limit only in their session
860            // files (hive-mind#3570)
861            let rollout_options =
862                CodexRolloutOptions::for_run_env(&self.options.extra_env, &self.options.unset_env);
863            codex_rollout::apply_codex_rollout_usage_limit(&mut metadata, &rollout_options);
864            codex_rollout::apply_codex_rollout_usage_windows(&mut metadata, &rollout_options);
865            codex_rollout::apply_codex_rollout_context_usage(&mut metadata, &rollout_options);
866            if (self.options.json || self.options.tool == "agent")
867                && is_tool_supported(&self.options.tool)
868            {
869                completion::require_completed_result(
870                    &mut metadata,
871                    &self.options.tool,
872                    parsed_output.as_deref().unwrap_or_default(),
873                );
874            }
875            claude_transcript::apply_claude_transcript_usage_limit(
876                &mut metadata,
877                &ClaudeTranscriptOptions::for_run_env(
878                    &self.options.working_directory,
879                    &self.options.extra_env,
880                    &self.options.unset_env,
881                ),
882            );
883
884            let result = AgentResult {
885                exit_code,
886                plain_output,
887                parsed_output,
888                session_id: self.session_id.clone(),
889                usage,
890                metadata,
891            };
892            self.cleanup_prompt_temp_dir().await;
893            return Ok(result);
894        }
895
896        Err(format!(
897            "Unsupported isolation mode: {}",
898            self.options.isolation
899        ))
900    }
901
902    /// Cancel a running process and collect its final output and metadata.
903    ///
904    /// A process cancelled after its final result is judged by that result.
905    pub async fn cancel(&mut self) -> Result<AgentResult, String> {
906        let mut terminated_after_result = false;
907        if self.options.isolation == "none" || self.options.isolation.is_empty() {
908            if let Some(handle) = self.process_handle.as_mut() {
909                let mut reader = StdoutMessageReader::new();
910                terminated_after_result = !handle.try_wait().map_err(|e| e.to_string())?
911                    && has_final_result(&self.options.tool, reader.read(&handle.peek_stdout()));
912                handle
913                    .terminate()
914                    .await
915                    .map_err(|error| error.to_string())?;
916            }
917        }
918        self.stop(AgentStopOptions {
919            terminated_after_result,
920            ..Default::default()
921        })
922        .await
923    }
924
925    /// Get the current session ID (if available)
926    pub fn get_session_id(&self) -> Option<&String> {
927        self.session_id.as_ref()
928    }
929
930    /// Get all collected messages from the output stream
931    pub fn get_messages(&self) -> Vec<&Value> {
932        if let Some(ref stream) = self.output_stream {
933            stream.get_messages().iter().collect()
934        } else {
935            Vec::new()
936        }
937    }
938}
939
940/// Create an agent controller (convenience function)
941///
942/// # Arguments
943/// * `options` - Agent configuration
944///
945/// # Returns
946/// Result with Agent or error message
947pub fn agent(options: AgentOptions) -> Result<Agent, String> {
948    Agent::new(options)
949}
950
951// Tests are in rust/tests/lib_tests.rs
952
953#[cfg(test)]
954mod prompt_dir_tests {
955    use super::{create_prompt_temp_dir, write_prompt_file, PROMPT_DIR_SEQUENCE};
956    use std::sync::atomic::Ordering;
957
958    #[tokio::test]
959    async fn prompt_dirs_are_unique_within_one_clock_tick() {
960        let parent = tempfile::tempdir().expect("parent directory");
961        let first = create_prompt_temp_dir(parent.path(), 7).await.unwrap();
962        let second = create_prompt_temp_dir(parent.path(), 7).await.unwrap();
963        assert_ne!(first, second);
964        assert!(first.is_dir() && second.is_dir());
965    }
966
967    #[tokio::test]
968    async fn existing_prompt_dir_names_are_skipped() {
969        let parent = tempfile::tempdir().expect("parent directory");
970        let next = PROMPT_DIR_SEQUENCE.load(Ordering::Relaxed);
971        for sequence in next..next + 3 {
972            std::fs::create_dir(parent.path().join(format!(
973                "agent-commander-{}-9-{sequence}",
974                std::process::id()
975            )))
976            .unwrap();
977        }
978        let dir = create_prompt_temp_dir(parent.path(), 9).await.unwrap();
979        assert!(dir.is_dir());
980        assert_eq!(std::fs::read_dir(parent.path()).unwrap().count(), 4);
981    }
982
983    /// A tokio `File` writes at most 2 MiB per background operation, so a
984    /// larger prompt must be complete before the agent is spawned to read it.
985    #[tokio::test]
986    async fn large_prompt_files_are_complete_when_written() {
987        let parent = tempfile::tempdir().expect("parent directory");
988        let content = "x".repeat(3 * 1024 * 1024 + 37);
989        for attempt in 0..20 {
990            let path = parent.path().join(format!("prompt-{attempt}.txt"));
991            write_prompt_file(&path, &content).await.unwrap();
992            assert_eq!(
993                std::fs::metadata(&path).unwrap().len(),
994                content.len() as u64,
995                "attempt {attempt}"
996            );
997        }
998    }
999}