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 error_text;
19pub mod executor;
20pub mod file_tail;
21pub mod permissions;
22pub mod result_close;
23pub mod result_metadata;
24pub mod streaming;
25pub mod tools;
26pub mod tui;
27pub mod usage_limit;
28
29use serde_json::Value;
30use std::path::{Path, PathBuf};
31use std::sync::atomic::{AtomicU64, Ordering};
32use std::time::{SystemTime, UNIX_EPOCH};
33use tokio::io::AsyncWriteExt;
34
35pub use cli_parser::{
36    parse_args, parse_start_agent_args, parse_stop_agent_args, show_start_agent_help,
37    show_stop_agent_help, validate_start_agent_options, validate_stop_agent_options,
38    StartAgentOptions, StopAgentOptions, ValidationResult,
39};
40
41pub use command_builder::{
42    build_agent_command, build_docker_stop_command, build_piped_command, build_screen_stop_command,
43    read_only_unsupported_error, supports_read_only, AgentCommandOptions,
44};
45
46pub use permissions::{
47    ask_scope, ask_unsupported_error, build_permission_response, normalize_permission_request,
48    permission_parity, supports_ask, NormalizedPermissionRequest, PermissionParityRow,
49    PermissionRelay, ASK_DECISIONS, ASK_SUPPORTED_TOOLS,
50};
51
52pub use executor::{
53    execute_command, execute_detached, is_process_group_alive, normalize_exit,
54    setup_signal_handler, signal_from_exit_code, signal_name, start_command, ExecutionResult,
55    ProcessHandle, DEFAULT_KILL_AFTER, DEFAULT_PIPE_DRAIN,
56};
57
58pub use background_tasks::{
59    assess_background_tasks, extract_observed_models, is_real_model_id, print_wait_ceiling_seconds,
60    track_background_tasks, BackgroundTask, BackgroundTaskAssessment, BackgroundTaskState,
61    StoppedBackgroundTask, PRINT_BG_CEILING_PATTERN,
62};
63
64pub use result_close::{
65    has_final_result, wait_for_exit_after_result, ResultCloseOptions, StdoutMessageReader,
66    DEFAULT_RESULT_POLL,
67};
68
69pub use codex_rollout::{
70    apply_codex_rollout_usage_limit, can_resume_codex_session, classify_codex_rate_limit_snapshot,
71    codex_rollout_limit_facts, codex_sessions_dir, detect_codex_rollout_usage_limit,
72    find_codex_rollout_file, is_codex_rollout_file_name, read_codex_rollout_limit_facts,
73    CodexLimitVerdict, CodexRolloutLimitFacts, CodexRolloutOptions, CODEX_ROLLOUT_LIMIT_SOURCE,
74    CODEX_SESSIONS_DIRNAME, ROLLOUT_TAIL_BYTES,
75};
76
77pub use claude_transcript::{
78    apply_claude_transcript_usage_limit, claude_project_slugs, claude_transcript_api_error,
79    claude_transcript_candidates, read_claude_transcript_api_error, ClaudeTranscriptApiError,
80    ClaudeTranscriptOptions, CLAUDE_TRANSCRIPT_LIMIT_SOURCE, TRANSCRIPT_TAIL_BYTES,
81};
82
83pub use file_tail::read_file_tail;
84
85pub use result_metadata::{
86    build_normalized_result_metadata, BuildMetadataOptions, PricingInfo, ResultMetadata,
87};
88
89pub use error_text::{first_error_text, stringify_error_value, MAX_ERROR_TEXT_LENGTH};
90
91pub use usage_limit::{
92    classify_debug_lines, classify_rate_limit_event, detect_usage_limit_sources,
93    extract_reset_time, extract_timezone, format_epoch_reset_time_utc, is_recoverable_tool_error,
94    is_usage_limit_text, limit_scan_text, DebugLines, UsageLimitVerdict,
95};
96
97pub use streaming::{
98    create_input_stream, create_output_stream, parse_json_records, parse_ndjson, parse_ndjson_line,
99    stringify_ndjson, stringify_ndjson_line, JsonInputStream, JsonOutputStream, JsonRecordEvent,
100    JsonRecordScanner, ParseError,
101};
102
103pub use tools::{
104    get_tool, is_tool_supported, list_tools, AgentTool, ClaudeTool, CodexTool, OpencodeTool, Tool,
105    ToolRegistry,
106};
107
108/// Agent options for creating a controller
109#[derive(Debug, Clone, Default)]
110pub struct AgentOptions {
111    /// CLI tool to use (e.g., 'claude', 'codex', 'opencode', 'agent', 'qwen', 'gemini')
112    pub tool: String,
113    /// Working directory for the agent
114    pub working_directory: String,
115    /// Prompt for the agent
116    pub prompt: Option<String>,
117    /// File containing prompt input for stdin-based tools
118    pub prompt_file: Option<String>,
119    /// System prompt for the agent
120    pub system_prompt: Option<String>,
121    /// Append to the default system prompt (tool-specific)
122    pub append_system_prompt: Option<String>,
123    /// Model to use (tool-specific)
124    pub model: Option<String>,
125    /// Fallback model to use when the primary model is overloaded (tool-specific)
126    pub fallback_model: Option<String>,
127    /// Isolation mode: 'none', 'screen', 'docker'
128    pub isolation: String,
129    /// Screen session name (for screen isolation)
130    pub screen_name: Option<String>,
131    /// Container name (for docker isolation)
132    pub container_name: Option<String>,
133    /// Enable JSON output mode
134    pub json: bool,
135    /// Resume a previous session (tool-specific)
136    pub resume: Option<String>,
137    /// Enable verbose output (tool-specific)
138    pub verbose: bool,
139    /// Re-emit user messages in streaming output (tool-specific)
140    pub replay_user_messages: bool,
141    /// Use a specific session ID (tool-specific)
142    pub session_id: Option<String>,
143    /// Fork a resumed session into a new session (tool-specific)
144    pub fork_session: bool,
145    /// Enforce native read-only/planning mode
146    pub read_only: bool,
147    /// Enforce native planning mode (where the tool distinguishes it)
148    pub plan_only: bool,
149    /// Approve each mutating command (ask mode), relayed over the tool's native
150    /// per-command JSON permission protocol (only `claude` and `agent`)
151    pub approve_each: bool,
152    /// Override the tool executable path/name
153    pub executable: Option<String>,
154    /// Extra raw arguments appended after typed tool arguments
155    pub extra_args: Vec<String>,
156    /// Extra environment variables applied to the tool executable
157    pub extra_env: Vec<(String, String)>,
158    /// Variables removed from the inherited environment of the tool
159    pub unset_env: Vec<String>,
160    /// Do not add default autonomous safety bypass flags
161    pub skip_default_safety_flags: bool,
162}
163
164/// Agent result from stop()
165#[derive(Debug, Clone, Default)]
166pub struct AgentResult {
167    /// Exit code from the process
168    pub exit_code: i32,
169    /// Plain text output (stdout + stderr)
170    pub plain_output: String,
171    /// Parsed JSON messages (if tool supports it)
172    pub parsed_output: Option<Vec<Value>>,
173    /// Session ID for resuming
174    pub session_id: Option<String>,
175    /// Aggregated stream token usage, when the tool exposes it
176    pub usage: Option<Value>,
177    /// Stable normalized metadata for caller reporting
178    pub metadata: ResultMetadata,
179}
180
181/// Agent start options
182#[derive(Debug, Clone, Default)]
183pub struct AgentStartOptions {
184    /// If true, just show the command
185    pub dry_run: bool,
186    /// Run in detached mode
187    pub detached: bool,
188    /// Stream output to console
189    pub attached: bool,
190}
191
192/// Agent stop options
193#[derive(Debug, Clone, Default)]
194pub struct AgentStopOptions {
195    /// If true, just show the command
196    pub dry_run: bool,
197    /// Stop a process that stays this long after its final result once no
198    /// background task runs (hive-mind#1280); `None` waits for it to exit
199    pub close_timeout: Option<std::time::Duration>,
200    /// Extra time a process may stay after its result while background tasks
201    /// run; `None` leaves them to the tool's own ceiling
202    pub background_wait: Option<std::time::Duration>,
203    /// The caller already stopped the process after its final result
204    pub terminated_after_result: bool,
205}
206
207/// Agent controller
208pub struct Agent {
209    options: AgentOptions,
210    process_handle: Option<ProcessHandle>,
211    output_stream: Option<JsonOutputStream>,
212    session_id: Option<String>,
213    prompt_temp_dir: Option<PathBuf>,
214}
215
216fn supports_prompt_file_input(tool: &str) -> bool {
217    matches!(
218        tool,
219        "claude" | "codex" | "opencode" | "agent" | "qwen" | "gemini"
220    )
221}
222
223fn build_prompt_file_content(
224    tool: &str,
225    prompt: Option<&str>,
226    system_prompt: Option<&str>,
227) -> String {
228    if tool == "claude" {
229        return prompt.unwrap_or_default().to_string();
230    }
231
232    match (system_prompt, prompt) {
233        (Some(system_prompt), Some(prompt)) => format!("{}\n\n{}", system_prompt, prompt),
234        (Some(system_prompt), None) => system_prompt.to_string(),
235        (None, Some(prompt)) => prompt.to_string(),
236        (None, None) => String::new(),
237    }
238}
239
240/// Names of prompt directories created by this process
241static PROMPT_DIR_SEQUENCE: AtomicU64 = AtomicU64::new(0);
242
243/// Names tried before a prompt directory is given up
244const PROMPT_DIR_ATTEMPTS: usize = 16;
245
246/// Create a new directory for a prompt file under `parent`.
247///
248/// The name holds the pid, the clock and a per-process sequence, because
249/// controllers started in parallel can read the same clock tick (macOS clocks
250/// are coarse). A name that already exists, such as a leftover from a reused
251/// pid, is skipped.
252async fn create_prompt_temp_dir(parent: &Path, nanos: u128) -> Result<PathBuf, String> {
253    for _ in 0..PROMPT_DIR_ATTEMPTS {
254        let sequence = PROMPT_DIR_SEQUENCE.fetch_add(1, Ordering::Relaxed);
255        let dir = parent.join(format!(
256            "agent-commander-{}-{nanos}-{sequence}",
257            std::process::id()
258        ));
259        match tokio::fs::create_dir(&dir).await {
260            Ok(()) => return Ok(dir),
261            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
262            Err(error) => return Err(error.to_string()),
263        }
264    }
265    Err(format!(
266        "could not create a prompt directory in {}",
267        parent.display()
268    ))
269}
270
271fn should_create_prompt_file(options: &AgentOptions, dry_run: bool) -> bool {
272    if dry_run || options.prompt_file.is_some() || !supports_prompt_file_input(&options.tool) {
273        return false;
274    }
275
276    if options.tool == "claude" {
277        return options.prompt.is_some();
278    }
279
280    options.prompt.is_some() || options.system_prompt.is_some()
281}
282
283fn extract_usage_value(tool: &str, output: &str) -> Option<Value> {
284    match tool {
285        "claude" => serde_json::to_value(tools::claude::extract_usage(output)).ok(),
286        "codex" => serde_json::to_value(tools::codex::extract_usage(output)).ok(),
287        "opencode" => serde_json::to_value(tools::opencode::extract_usage(output)).ok(),
288        "agent" => serde_json::to_value(tools::agent::extract_usage(output)).ok(),
289        "qwen" => serde_json::to_value(tools::qwen::extract_usage(output)).ok(),
290        "gemini" => serde_json::to_value(tools::gemini::extract_usage(output)).ok(),
291        _ => None,
292    }
293}
294
295impl Agent {
296    /// Create a new agent controller
297    ///
298    /// # Arguments
299    /// * `options` - Agent configuration
300    ///
301    /// # Returns
302    /// Result with Agent or error message
303    pub fn new(options: AgentOptions) -> Result<Self, String> {
304        // Validate required options
305        if options.tool.is_empty() {
306            return Err("tool is required".to_string());
307        }
308        if options.working_directory.is_empty() {
309            return Err("working_directory is required".to_string());
310        }
311        if options.isolation == "screen" && options.screen_name.is_none() {
312            return Err("screen_name is required for screen isolation".to_string());
313        }
314        if options.isolation == "docker" && options.container_name.is_none() {
315            return Err("container_name is required for docker isolation".to_string());
316        }
317        if (options.read_only || options.plan_only) && !supports_read_only(&options.tool) {
318            return Err(read_only_unsupported_error(&options.tool));
319        }
320        if options.approve_each && !supports_ask(&options.tool) {
321            return Err(ask_unsupported_error(&options.tool));
322        }
323
324        Ok(Self {
325            options,
326            process_handle: None,
327            output_stream: None,
328            session_id: None,
329            prompt_temp_dir: None,
330        })
331    }
332
333    async fn cleanup_prompt_temp_dir(&mut self) {
334        if let Some(dir) = self.prompt_temp_dir.take() {
335            let _ = tokio::fs::remove_dir_all(dir).await;
336        }
337    }
338
339    async fn prepare_prompt_file(&mut self, dry_run: bool) -> Result<Option<String>, String> {
340        if !should_create_prompt_file(&self.options, dry_run) {
341            return Ok(self.options.prompt_file.clone());
342        }
343
344        let nanos = SystemTime::now()
345            .duration_since(UNIX_EPOCH)
346            .map_err(|e| e.to_string())?
347            .as_nanos();
348        let temp_dir = create_prompt_temp_dir(&std::env::temp_dir(), nanos).await?;
349        self.prompt_temp_dir = Some(temp_dir.clone());
350        let prompt_file = temp_dir.join("prompt.txt");
351        let content = build_prompt_file_content(
352            &self.options.tool,
353            self.options.prompt.as_deref(),
354            self.options.system_prompt.as_deref(),
355        );
356
357        let mut open_options = tokio::fs::OpenOptions::new();
358        open_options.write(true).create_new(true);
359        #[cfg(unix)]
360        {
361            open_options.mode(0o600);
362        }
363        let mut file = open_options
364            .open(&prompt_file)
365            .await
366            .map_err(|e| e.to_string())?;
367        file.write_all(content.as_bytes())
368            .await
369            .map_err(|e| e.to_string())?;
370
371        Ok(Some(prompt_file.to_string_lossy().into_owned()))
372    }
373
374    /// Start the agent (non-blocking)
375    ///
376    /// # Arguments
377    /// * `start_options` - Start options
378    ///
379    /// # Returns
380    /// Result indicating success or error
381    pub async fn start(&mut self, start_options: AgentStartOptions) -> Result<(), String> {
382        // Create output stream for JSON parsing if in JSON mode
383        if self.options.json {
384            self.output_stream = Some(create_output_stream());
385        }
386
387        let prepared_prompt_file = match self.prepare_prompt_file(start_options.dry_run).await {
388            Ok(prompt_file) => prompt_file,
389            Err(error) => {
390                self.cleanup_prompt_temp_dir().await;
391                return Err(error);
392            }
393        };
394        let prompt_handled_by_temp_file =
395            prepared_prompt_file.is_some() && self.options.prompt_file.is_none();
396
397        // Build the command
398        let command_options = AgentCommandOptions {
399            tool: self.options.tool.clone(),
400            working_directory: self.options.working_directory.clone(),
401            prompt: if prompt_handled_by_temp_file {
402                None
403            } else {
404                self.options.prompt.clone()
405            },
406            prompt_file: prepared_prompt_file,
407            system_prompt: if prompt_handled_by_temp_file && self.options.tool != "claude" {
408                None
409            } else {
410                self.options.system_prompt.clone()
411            },
412            append_system_prompt: self.options.append_system_prompt.clone(),
413            model: self.options.model.clone(),
414            fallback_model: self.options.fallback_model.clone(),
415            json: self.options.json,
416            verbose: self.options.verbose,
417            replay_user_messages: self.options.replay_user_messages,
418            resume: self.options.resume.clone(),
419            session_id: self.options.session_id.clone(),
420            fork_session: self.options.fork_session,
421            read_only: self.options.read_only,
422            plan_only: self.options.plan_only,
423            approve_each: self.options.approve_each,
424            executable: self.options.executable.clone(),
425            extra_args: self.options.extra_args.clone(),
426            extra_env: self.options.extra_env.clone(),
427            unset_env: self.options.unset_env.clone(),
428            skip_default_safety_flags: self.options.skip_default_safety_flags,
429            isolation: self.options.isolation.clone(),
430            screen_name: self.options.screen_name.clone(),
431            container_name: self.options.container_name.clone(),
432            detached: start_options.detached,
433        };
434
435        let command = build_agent_command(&command_options);
436
437        if start_options.dry_run {
438            println!("Dry run - command that would be executed:");
439            println!("{}", command);
440            return Ok(());
441        }
442
443        if start_options.detached {
444            // For detached mode, use execute_detached
445            if let Err(error) = execute_detached(&command).await.map_err(|e| e.to_string()) {
446                self.cleanup_prompt_temp_dir().await;
447                return Err(error);
448            }
449            println!("Agent started in detached mode");
450            if self.options.isolation == "screen" {
451                if let Some(ref name) = self.options.screen_name {
452                    println!("Screen session: {}", name);
453                }
454            } else if self.options.isolation == "docker" {
455                if let Some(ref name) = self.options.container_name {
456                    println!("Container: {}", name);
457                }
458            }
459        } else {
460            // For attached mode, start command without waiting
461            let handle = match start_command(&command, start_options.attached)
462                .await
463                .map_err(|e| e.to_string())
464            {
465                Ok(handle) => handle,
466                Err(error) => {
467                    self.cleanup_prompt_temp_dir().await;
468                    return Err(error);
469                }
470            };
471            self.process_handle = Some(handle);
472        }
473
474        Ok(())
475    }
476
477    /// Stop the agent and collect output
478    ///
479    /// # Arguments
480    /// * `stop_options` - Stop options
481    ///
482    /// # Returns
483    /// Result with agent output or error
484    pub async fn stop(&mut self, stop_options: AgentStopOptions) -> Result<AgentResult, String> {
485        // For isolation modes, send stop command
486        if self.options.isolation == "screen" || self.options.isolation == "docker" {
487            let stop_command = if self.options.isolation == "screen" {
488                let screen_name = self
489                    .options
490                    .screen_name
491                    .as_ref()
492                    .ok_or("screen_name is required to stop screen session")?;
493                build_screen_stop_command(screen_name)
494            } else {
495                let container_name = self
496                    .options
497                    .container_name
498                    .as_ref()
499                    .ok_or("container_name is required to stop docker container")?;
500                build_docker_stop_command(container_name)
501            };
502
503            if stop_options.dry_run {
504                println!("Dry run - command that would be executed:");
505                println!("{}", stop_command);
506                return Ok(AgentResult {
507                    metadata: build_normalized_result_metadata(BuildMetadataOptions {
508                        tool: &self.options.tool,
509                        exit_code: 0,
510                        plain_output: "",
511                        parsed_output: None,
512                        session_id: None,
513                        usage: None,
514                        ..Default::default()
515                    }),
516                    ..Default::default()
517                });
518            }
519
520            let result = match execute_command(&stop_command, false, true)
521                .await
522                .map_err(|e| e.to_string())
523            {
524                Ok(result) => result,
525                Err(error) => {
526                    self.cleanup_prompt_temp_dir().await;
527                    return Err(error);
528                }
529            };
530            self.cleanup_prompt_temp_dir().await;
531
532            let metadata = build_normalized_result_metadata(BuildMetadataOptions {
533                tool: &self.options.tool,
534                exit_code: result.exit_code,
535                plain_output: &result.stdout,
536                parsed_output: None,
537                session_id: None,
538                usage: None,
539                signal: result.signal.clone(),
540                ..Default::default()
541            });
542
543            return Ok(AgentResult {
544                exit_code: result.exit_code,
545                plain_output: result.stdout,
546                parsed_output: None,
547                session_id: None,
548                usage: None,
549                metadata,
550            });
551        }
552
553        // For no isolation, wait for process to complete and collect output
554        if self.options.isolation == "none" || self.options.isolation.is_empty() {
555            if self.process_handle.is_none() {
556                self.cleanup_prompt_temp_dir().await;
557                return Err("Agent not started or already stopped".to_string());
558            }
559            let handle = self
560                .process_handle
561                .as_mut()
562                .ok_or("Agent not started or already stopped")?;
563
564            // Wait for the process to exit, closing it when it outlives its result
565            let close = ResultCloseOptions {
566                close_timeout: stop_options.close_timeout,
567                background_wait: stop_options.background_wait,
568                ..Default::default()
569            };
570            let waited = wait_for_exit_after_result(handle, &self.options.tool, close).await;
571            let (exit_code, terminated_after_result) = match waited.map_err(|e| e.to_string()) {
572                Ok((exit_code, terminated)) => (
573                    exit_code,
574                    terminated || stop_options.terminated_after_result,
575                ),
576                Err(error) => {
577                    self.cleanup_prompt_temp_dir().await;
578                    return Err(error);
579                }
580            };
581
582            let (stdout, stderr, _) = handle.get_output();
583
584            // Combine stdout and stderr for plain output
585            let plain_output = if stderr.is_empty() {
586                stdout.to_string()
587            } else {
588                format!("{}\n{}", stdout, stderr)
589            };
590
591            // Process output through stream if available
592            let mut parsed_output = None;
593            if let Some(ref mut stream) = self.output_stream {
594                stream.process(stdout);
595                stream.flush();
596                let messages = stream.get_messages();
597                if !messages.is_empty() {
598                    parsed_output = Some(messages.to_vec());
599                }
600            }
601
602            if parsed_output.is_none() {
603                parsed_output = Some(if self.options.tool == "gemini" {
604                    tools::gemini::parse_output(stdout)
605                } else {
606                    streaming::parse_json_records(stdout)
607                });
608            }
609
610            // Try to extract session ID
611            if is_tool_supported(&self.options.tool) {
612                match self.options.tool.as_str() {
613                    "claude" => {
614                        self.session_id = tools::claude::extract_session_id(stdout);
615                    }
616                    "codex" => {
617                        self.session_id = tools::codex::extract_session_id(stdout);
618                    }
619                    "opencode" => {
620                        self.session_id = tools::opencode::extract_session_id(stdout);
621                    }
622                    "agent" => {
623                        self.session_id = tools::agent::extract_session_id(stdout);
624                    }
625                    "qwen" => self.session_id = tools::qwen::extract_session_id(stdout),
626                    "gemini" => self.session_id = tools::gemini::extract_session_id(stdout),
627                    _ => {}
628                }
629            }
630
631            let usage = extract_usage_value(&self.options.tool, stdout);
632            let mut metadata = build_normalized_result_metadata(BuildMetadataOptions {
633                tool: &self.options.tool,
634                exit_code,
635                plain_output: &plain_output,
636                parsed_output: parsed_output.as_deref(),
637                session_id: self.session_id.clone(),
638                usage: usage.clone(),
639                signal: handle.signal().map(String::from),
640                terminated_after_result,
641            });
642            // Codex and Claude can leave a usage limit only in their session
643            // files (hive-mind#3570)
644            codex_rollout::apply_codex_rollout_usage_limit(
645                &mut metadata,
646                &CodexRolloutOptions::for_run_env(&self.options.extra_env, &self.options.unset_env),
647            );
648            if (self.options.json || self.options.tool == "agent")
649                && is_tool_supported(&self.options.tool)
650            {
651                completion::require_completed_result(
652                    &mut metadata,
653                    &self.options.tool,
654                    parsed_output.as_deref().unwrap_or_default(),
655                );
656            }
657            claude_transcript::apply_claude_transcript_usage_limit(
658                &mut metadata,
659                &ClaudeTranscriptOptions::for_run_env(
660                    &self.options.working_directory,
661                    &self.options.extra_env,
662                    &self.options.unset_env,
663                ),
664            );
665
666            let result = AgentResult {
667                exit_code,
668                plain_output,
669                parsed_output,
670                session_id: self.session_id.clone(),
671                usage,
672                metadata,
673            };
674            self.cleanup_prompt_temp_dir().await;
675            return Ok(result);
676        }
677
678        Err(format!(
679            "Unsupported isolation mode: {}",
680            self.options.isolation
681        ))
682    }
683
684    /// Cancel a running process and collect its final output and metadata.
685    ///
686    /// A process cancelled after its final result is judged by that result.
687    pub async fn cancel(&mut self) -> Result<AgentResult, String> {
688        let mut terminated_after_result = false;
689        if self.options.isolation == "none" || self.options.isolation.is_empty() {
690            if let Some(handle) = self.process_handle.as_mut() {
691                let mut reader = StdoutMessageReader::new();
692                terminated_after_result = !handle.try_wait().map_err(|e| e.to_string())?
693                    && has_final_result(&self.options.tool, reader.read(&handle.peek_stdout()));
694                handle
695                    .terminate()
696                    .await
697                    .map_err(|error| error.to_string())?;
698            }
699        }
700        self.stop(AgentStopOptions {
701            terminated_after_result,
702            ..Default::default()
703        })
704        .await
705    }
706
707    /// Get the current session ID (if available)
708    pub fn get_session_id(&self) -> Option<&String> {
709        self.session_id.as_ref()
710    }
711
712    /// Get all collected messages from the output stream
713    pub fn get_messages(&self) -> Vec<&Value> {
714        if let Some(ref stream) = self.output_stream {
715            stream.get_messages().iter().collect()
716        } else {
717            Vec::new()
718        }
719    }
720}
721
722/// Create an agent controller (convenience function)
723///
724/// # Arguments
725/// * `options` - Agent configuration
726///
727/// # Returns
728/// Result with Agent or error message
729pub fn agent(options: AgentOptions) -> Result<Agent, String> {
730    Agent::new(options)
731}
732
733// Tests are in rust/tests/lib_tests.rs
734
735#[cfg(test)]
736mod prompt_dir_tests {
737    use super::{create_prompt_temp_dir, PROMPT_DIR_SEQUENCE};
738    use std::sync::atomic::Ordering;
739
740    #[tokio::test]
741    async fn prompt_dirs_are_unique_within_one_clock_tick() {
742        let parent = tempfile::tempdir().expect("parent directory");
743        let first = create_prompt_temp_dir(parent.path(), 7).await.unwrap();
744        let second = create_prompt_temp_dir(parent.path(), 7).await.unwrap();
745        assert_ne!(first, second);
746        assert!(first.is_dir() && second.is_dir());
747    }
748
749    #[tokio::test]
750    async fn existing_prompt_dir_names_are_skipped() {
751        let parent = tempfile::tempdir().expect("parent directory");
752        let next = PROMPT_DIR_SEQUENCE.load(Ordering::Relaxed);
753        for sequence in next..next + 3 {
754            std::fs::create_dir(parent.path().join(format!(
755                "agent-commander-{}-9-{sequence}",
756                std::process::id()
757            )))
758            .unwrap();
759        }
760        let dir = create_prompt_temp_dir(parent.path(), 9).await.unwrap();
761        assert!(dir.is_dir());
762        assert_eq!(std::fs::read_dir(parent.path()).unwrap().count(), 4);
763    }
764}