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