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