Skip to main content

agent_commander/
lib.rs

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