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