agent-commander 0.7.0

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! Agent Commander - Main library interface
//! A Rust library to control agents enclosed in CLI commands
//!
//! Supports multiple CLI agents:
//! - claude: Anthropic Claude Code CLI
//! - codex: OpenAI Codex CLI
//! - opencode: OpenCode CLI
//! - agent: @link-assistant/agent (OpenCode fork with native permission modes)
//! - qwen: Qwen Code CLI
//! - gemini: Gemini CLI

pub mod api_status;
pub mod background_tasks;
pub mod claude_transcript;
pub mod cli_parser;
pub mod codex_rollout;
pub mod command_builder;
mod completion;
pub mod context_usage;
pub mod docker;
mod isolation;
mod openai_compatible_gateway;
mod run_deadline;
pub use docker::DockerOptions;
use std::io::IsTerminal;
pub mod error_text;
pub mod executor;
pub mod file_tail;
pub mod live_input;
pub mod permissions;
pub mod result_close;
pub mod result_metadata;
pub mod streaming;
pub mod structured_output;
pub mod tool_overrides;
pub mod tool_version;
pub mod tools;
pub mod tui;
pub mod usage_limit;
pub mod usage_windows;

use serde_json::Value;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::io::AsyncWriteExt;

pub use cli_parser::{
    parse_args, parse_start_agent_args, parse_stop_agent_args, show_start_agent_help,
    show_stop_agent_help, validate_start_agent_options, validate_stop_agent_options,
    StartAgentOptions, StopAgentOptions, ValidationResult,
};

pub use command_builder::{
    build_agent_command, build_base_command, build_docker_stop_command, build_piped_command,
    build_screen_stop_command, read_only_unsupported_error, supports_read_only,
    AgentCommandOptions,
};

pub use permissions::{
    ask_scope, ask_unsupported_error, build_permission_response, normalize_permission_request,
    permission_parity, supports_ask, NormalizedPermissionRequest, PermissionParityRow,
    PermissionRelay, ASK_DECISIONS, ASK_SUPPORTED_TOOLS,
};

pub use tools::shell::{
    build_child_environment, build_child_environment_passing, file_content_arg, InheritEnv,
};

pub use executor::{
    execute_command, execute_detached, execute_detached_with_env, is_process_group_alive,
    normalize_exit, setup_signal_handler, signal_from_exit_code, signal_name, start_command,
    start_command_with_env, start_command_with_stdin, ExecutionResult, ProcessHandle,
    DEFAULT_KILL_AFTER, DEFAULT_PIPE_DRAIN,
};

pub use api_status::*;

pub use background_tasks::{
    assess_background_tasks, extract_observed_models, is_real_model_id, print_wait_ceiling_seconds,
    track_background_tasks, BackgroundTask, BackgroundTaskAssessment, BackgroundTaskState,
    StoppedBackgroundTask, PRINT_BG_CEILING_PATTERN,
};

pub use result_close::{
    has_final_result, wait_for_exit_after_result, watch_process_exit, ResultCloseOptions,
    ResultCloseOutcome, StdoutMessageReader, DEFAULT_RESULT_POLL,
};

pub use codex_rollout::{
    apply_codex_rollout_context_usage, apply_codex_rollout_usage_limit,
    apply_codex_rollout_usage_windows, can_resume_codex_session,
    classify_codex_rate_limit_snapshot, codex_rollout_context_usage, codex_rollout_limit_facts,
    codex_sessions_dir, detect_codex_rollout_usage_limit, find_codex_rollout_file,
    is_codex_rollout_file_name, read_codex_rollout_limit_facts, CodexLimitVerdict,
    CodexRolloutLimitFacts, CodexRolloutOptions, CODEX_ROLLOUT_LIMIT_SOURCE,
    CODEX_SESSIONS_DIRNAME, ROLLOUT_TAIL_BYTES,
};

pub use claude_transcript::{
    apply_claude_transcript_usage_limit, claude_project_slugs, claude_transcript_api_error,
    claude_transcript_candidates, read_claude_transcript_api_error, ClaudeTranscriptApiError,
    ClaudeTranscriptOptions, CLAUDE_TRANSCRIPT_LIMIT_SOURCE, TRANSCRIPT_TAIL_BYTES,
};

pub use context_usage::{
    claude_request_context_tokens, context_reading_from_message, extract_context_usage,
    ContextReading, ContextUsage,
};
pub use file_tail::read_file_tail;
pub use live_input::{
    build_interrupt_frame, build_user_input_frame, live_input_unsupported_error,
    supports_live_input,
};

pub use result_metadata::{
    build_normalized_result_metadata, BuildMetadataOptions, PricingInfo, ResultMetadata,
};

pub use error_text::{first_error_text, stringify_error_value, MAX_ERROR_TEXT_LENGTH};

pub use usage_limit::{
    classify_debug_lines, classify_rate_limit_event, detect_usage_limit_sources,
    extract_reset_time, extract_timezone, format_epoch_reset_time_utc, is_recoverable_tool_error,
    is_usage_limit_text, limit_scan_text, DebugLines, UsageLimitVerdict,
};

pub use structured_output::extract_structured_output;

pub use streaming::{
    create_input_stream, create_output_stream, parse_json_records, parse_ndjson, parse_ndjson_line,
    stringify_ndjson, stringify_ndjson_line, JsonInputStream, JsonOutputStream, JsonRecordEvent,
    JsonRecordScanner, ParseError,
};

pub use tools::{
    get_tool, is_tool_supported, list_tools, AgentTool, ClaudeTool, CodexTool, OpencodeTool, Tool,
    ToolRegistry,
};

pub use usage_windows::{
    claude_rate_limit_windows, codex_rate_limit_windows, extract_usage_windows,
    merge_usage_windows, usage_windows_from_message, UsageWindow, USAGE_WINDOW_KINDS,
};

/// Shell quoting for `ToolOverrides::build_command` implementations
pub use tools::shell::escape_arg;

pub use tool_overrides::{
    BuildCommandFn, ExtractSessionIdFn, ExtractUsageFn, ParseOutputFn, ToolOverrides,
};

pub use tool_version::{
    build_version_command, compare_versions, get_tool_version, parse_tool_version,
    tool_version_from_output, ToolVersion,
};

pub use tools::launch_options::{
    check_gateway_token, check_launch_options_against, check_launch_options_supported,
    claude_gateway_settings, codex_gateway_overrides, codex_mcp_servers_override, json_schema_arg,
    launch_capabilities, normalize_gateway, normalize_reasoning_effort, push_attachments,
    push_directories, resolve_gateway, to_toml_value, GatewayOptions, LaunchCapabilities,
    LaunchOptions, CLAUDE_GATEWAY_UNSET_ENV, CLAUDE_REASONING_EFFORTS, CODEX_GATEWAY_PROVIDER_ID,
    CODEX_REASONING_EFFORTS, ROUTER_SERVICE_PATHS,
};

/// Agent options for creating a controller
#[derive(Debug, Clone, Default)]
pub struct AgentOptions {
    /// CLI tool to use (e.g., 'claude', 'codex', 'opencode', 'agent', 'qwen', 'gemini')
    pub tool: String,
    /// Working directory for the agent
    pub working_directory: String,
    /// Prompt for the agent
    pub prompt: Option<String>,
    /// File containing prompt input for stdin-based tools
    pub prompt_file: Option<String>,
    /// System prompt for the agent
    pub system_prompt: Option<String>,
    /// Append to the default system prompt (tool-specific)
    pub append_system_prompt: Option<String>,
    /// Model to use (tool-specific)
    pub model: Option<String>,
    /// Fallback model to use when the primary model is overloaded (tool-specific)
    pub fallback_model: Option<String>,
    /// Isolation mode: 'none', 'screen', 'docker'
    pub isolation: String,
    /// Screen session name (for screen isolation)
    pub screen_name: Option<String>,
    /// Container name (for docker isolation)
    pub container_name: Option<String>,
    /// Docker image and run flags.
    pub docker: DockerOptions,
    /// Optional overall attached run deadline.
    pub timeout: Option<std::time::Duration>,
    /// Enable JSON output mode
    pub json: bool,
    /// Resume a previous session (tool-specific)
    pub resume: Option<String>,
    /// Enable verbose output (tool-specific)
    pub verbose: bool,
    /// Re-emit user messages in streaming output (tool-specific)
    pub replay_user_messages: bool,
    /// Use a specific session ID (tool-specific)
    pub session_id: Option<String>,
    /// Fork a resumed session into a new session (tool-specific)
    pub fork_session: bool,
    /// Enforce native read-only/planning mode
    pub read_only: bool,
    /// Enforce native planning mode (where the tool distinguishes it)
    pub plan_only: bool,
    /// Approve each mutating command (ask mode), relayed over the tool's native
    /// per-command JSON permission protocol (only `claude` and `agent`)
    pub approve_each: bool,
    /// Override the tool executable path/name
    pub executable: Option<String>,
    /// Extra raw arguments appended after typed tool arguments
    pub extra_args: Vec<String>,
    /// Extra environment variables applied to the tool executable
    pub extra_env: Vec<(String, String)>,
    /// Variables removed from the inherited environment of the tool
    pub unset_env: Vec<String>,
    /// Which host variables the tool inherits: all (default), none, or an
    /// allowlist (issue #60)
    pub inherit_env: InheritEnv,
    /// Explicit environment replacing the inherited one; `extra_env` and
    /// `unset_env` still apply on top (issue #60)
    pub env: Option<Vec<(String, String)>>,
    /// Do not add default autonomous safety bypass flags
    pub skip_default_safety_flags: bool,
    /// Shared launch options: generation controls, reasoning effort, MCP servers, strict MCP
    /// configuration, extra workspace directories, attachments and a JSON
    /// Schema for structured output
    pub launch: LaunchOptions,
    /// Keep stdin open for [`Agent::send_message`] and [`Agent::interrupt`]
    /// (`claude`, `qwen`, `agent`; attached runs without isolation). The
    /// prompt becomes the first stream-json frame and JSON output is forced.
    pub live_input: bool,
    /// Stop on a Claude 401/403 `api_retry` as `auth_refused` (#69); `None`: on with a gateway
    pub fail_fast_on_auth_error: Option<bool>,
    /// Replace the command builder, output parser, session ID or usage
    /// extractor, or launch capabilities for this run
    pub tool_overrides: ToolOverrides,
}

/// Agent result from stop()
#[derive(Debug, Clone, Default)]
pub struct AgentResult {
    /// Exit code from the process, or `None` if its run deadline expired.
    pub exit_code: Option<i32>,
    /// Normalized error type, including `timeout` on deadline expiry.
    pub error_type: Option<String>,
    /// Plain text output (stdout + stderr)
    pub plain_output: String,
    /// Parsed JSON messages (if tool supports it)
    pub parsed_output: Option<Vec<Value>>,
    /// Session ID for resuming
    pub session_id: Option<String>,
    /// Aggregated stream token usage, when the tool exposes it
    pub usage: Option<Value>,
    /// Stable normalized metadata for caller reporting
    pub metadata: ResultMetadata,
}

/// Agent start options
#[derive(Debug, Clone, Default)]
pub struct AgentStartOptions {
    /// If true, just show the command
    pub dry_run: bool,
    /// Run in detached mode
    pub detached: bool,
    /// Stream output to console
    pub attached: bool,
    /// Overall deadline, overriding the controller's default.
    pub timeout: Option<std::time::Duration>,
    /// Grace before killing a timed-out run, and time to wait after a result.
    pub close_timeout: Option<std::time::Duration>,
}

/// Agent stop options
#[derive(Debug, Clone, Default)]
pub struct AgentStopOptions {
    /// If true, just show the command
    pub dry_run: bool,
    /// Stop a process that stays this long after its final result once no
    /// background task runs (hive-mind#1280); `None` waits for it to exit
    pub close_timeout: Option<std::time::Duration>,
    /// Extra time a process may stay after its result while background tasks
    /// run; `None` leaves them to the tool's own ceiling
    pub background_wait: Option<std::time::Duration>,
    /// The caller already stopped the process after its final result
    pub terminated_after_result: bool,
}

/// Agent controller
pub struct Agent {
    options: AgentOptions,
    process_handle: Option<ProcessHandle>,
    output_stream: Option<JsonOutputStream>,
    session_id: Option<String>,
    prompt_temp_dir: Option<PathBuf>,
    close_timeout: Option<std::time::Duration>,
}

fn supports_prompt_file_input(tool: &str) -> bool {
    matches!(
        tool,
        "claude" | "codex" | "opencode" | "agent" | "qwen" | "gemini"
    )
}

fn build_prompt_file_content(
    tool: &str,
    prompt: Option<&str>,
    system_prompt: Option<&str>,
) -> String {
    if tool == "claude" {
        return prompt.unwrap_or_default().to_string();
    }

    match (system_prompt, prompt) {
        (Some(system_prompt), Some(prompt)) => format!("{}\n\n{}", system_prompt, prompt),
        (Some(system_prompt), None) => system_prompt.to_string(),
        (None, Some(prompt)) => prompt.to_string(),
        (None, None) => String::new(),
    }
}

/// Names of prompt directories created by this process
static PROMPT_DIR_SEQUENCE: AtomicU64 = AtomicU64::new(0);

/// Names tried before a prompt directory is given up
const PROMPT_DIR_ATTEMPTS: usize = 16;

/// Create a new directory for a prompt file under `parent`.
///
/// The name holds the pid, the clock and a per-process sequence, because
/// controllers started in parallel can read the same clock tick (macOS clocks
/// are coarse). A name that already exists, such as a leftover from a reused
/// pid, is skipped.
async fn create_prompt_temp_dir(parent: &Path, nanos: u128) -> Result<PathBuf, String> {
    for _ in 0..PROMPT_DIR_ATTEMPTS {
        let sequence = PROMPT_DIR_SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let dir = parent.join(format!(
            "agent-commander-{}-{nanos}-{sequence}",
            std::process::id()
        ));
        match tokio::fs::create_dir(&dir).await {
            Ok(()) => return Ok(dir),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(error) => return Err(error.to_string()),
        }
    }
    Err(format!(
        "could not create a prompt directory in {}",
        parent.display()
    ))
}

/// Write a new, owner-only prompt file and return once all of it is on disk.
async fn write_prompt_file(path: &Path, content: &str) -> Result<(), String> {
    let mut open_options = tokio::fs::OpenOptions::new();
    open_options.write(true).create_new(true);
    #[cfg(unix)]
    {
        open_options.mode(0o600);
    }
    let mut file = open_options.open(path).await.map_err(|e| e.to_string())?;
    file.write_all(content.as_bytes())
        .await
        .map_err(|e| e.to_string())?;
    // tokio writes at most 2 MiB per background operation and `write_all`
    // returns once the last one is queued; `flush` waits for it to finish.
    file.flush().await.map_err(|e| e.to_string())
}

fn should_create_prompt_file(options: &AgentOptions, dry_run: bool) -> bool {
    if dry_run || options.prompt_file.is_some() || !supports_prompt_file_input(&options.tool) {
        return false;
    }

    if options.tool == "claude" {
        return options.prompt.is_some();
    }

    options.prompt.is_some() || options.system_prompt.is_some()
}

fn extract_usage_value(tool: &str, output: &str) -> Option<Value> {
    match tool {
        "claude" => serde_json::to_value(tools::claude::extract_usage(output)).ok(),
        "codex" => serde_json::to_value(tools::codex::extract_usage(output)).ok(),
        "opencode" => serde_json::to_value(tools::opencode::extract_usage(output)).ok(),
        "agent" => serde_json::to_value(tools::agent::extract_usage(output)).ok(),
        "qwen" => serde_json::to_value(tools::qwen::extract_usage(output)).ok(),
        "gemini" => serde_json::to_value(tools::gemini::extract_usage(output)).ok(),
        _ => None,
    }
}

impl Agent {
    /// Create a new agent controller
    ///
    /// # Arguments
    /// * `options` - Agent configuration
    ///
    /// # Returns
    /// Result with Agent or error message
    pub fn new(options: AgentOptions) -> Result<Self, String> {
        if options.tool.is_empty() {
            return Err("tool is required".to_string());
        }
        if options.working_directory.is_empty() {
            return Err("working_directory is required".to_string());
        }
        if options.isolation == "screen" && options.screen_name.is_none() {
            return Err("screen_name is required for screen isolation".to_string());
        }
        if options.isolation == "docker" && options.container_name.is_none() {
            return Err("container_name is required for docker isolation".to_string());
        }
        if (options.read_only || options.plan_only) && !supports_read_only(&options.tool) {
            return Err(read_only_unsupported_error(&options.tool));
        }
        if options.approve_each && !supports_ask(&options.tool) {
            return Err(ask_unsupported_error(&options.tool));
        }

        Ok(Self {
            options,
            process_handle: None,
            output_stream: None,
            session_id: None,
            prompt_temp_dir: None,
            close_timeout: None,
        })
    }

    async fn cleanup_prompt_temp_dir(&mut self) {
        if let Some(dir) = self.prompt_temp_dir.take() {
            let _ = tokio::fs::remove_dir_all(dir).await;
        }
    }

    /// The tool's environment: `extra_env` values travel through `spawn`,
    /// never through the command line (issue #60). The gateway token
    /// variable is always inherited (issue #65).
    fn child_environment(&self) -> Result<Vec<(String, String)>, String> {
        let pass_env: Vec<String> = self
            .options
            .launch
            .gateway
            .iter()
            .map(|gateway| gateway.token_env.clone())
            .collect();
        build_child_environment_passing(
            std::env::vars(),
            &self.options.inherit_env,
            self.options.env.as_deref(),
            &pass_env,
            &self.options.unset_env,
            &self.options.extra_env,
        )
    }

    async fn ensure_prompt_temp_dir(&mut self) -> Result<PathBuf, String> {
        if let Some(dir) = &self.prompt_temp_dir {
            return Ok(dir.clone());
        }
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| e.to_string())?
            .as_nanos();
        let dir = create_prompt_temp_dir(&std::env::temp_dir(), nanos).await?;
        self.prompt_temp_dir = Some(dir.clone());
        Ok(dir)
    }

    /// Write system prompts and the JSON Schema to owner-only files so they
    /// stay out of `ps` / `/proc/<pid>/cmdline` and argv limits (issue #60).
    async fn move_inline_values_to_files(
        &mut self,
        options: &mut AgentCommandOptions,
    ) -> Result<(), String> {
        let claude = options.tool == "claude";
        let schema_tool = matches!(options.tool.as_str(), "claude" | "codex" | "qwen");
        let mut files: Vec<(&str, String)> = Vec::new();
        if claude {
            if let Some(text) = options.system_prompt.clone().filter(|t| !t.is_empty()) {
                files.push(("system-prompt.txt", text));
            }
            if let Some(text) = options
                .append_system_prompt
                .clone()
                .filter(|t| !t.is_empty())
            {
                files.push(("append-system-prompt.txt", text));
            }
        }
        if schema_tool {
            if let Some(schema) = options.launch.json_schema.clone() {
                files.push(("schema.json", json_schema_arg(&schema)));
            }
        }
        if files.is_empty() {
            return Ok(());
        }
        let dir = self.ensure_prompt_temp_dir().await?;
        for (name, content) in files {
            let path = dir.join(name);
            write_prompt_file(&path, &content).await?;
            let path = path.to_string_lossy().into_owned();
            match name {
                "system-prompt.txt" => options.launch.system_prompt_file = Some(path),
                "append-system-prompt.txt" => {
                    options.launch.append_system_prompt_file = Some(path);
                }
                _ => options.launch.json_schema_file = Some(path),
            }
        }
        Ok(())
    }

    async fn prepare_prompt_file(&mut self, dry_run: bool) -> Result<Option<String>, String> {
        if !should_create_prompt_file(&self.options, dry_run) {
            return Ok(self.options.prompt_file.clone());
        }

        let temp_dir = self.ensure_prompt_temp_dir().await?;
        let prompt_file = temp_dir.join("prompt.txt");
        let content = build_prompt_file_content(
            &self.options.tool,
            self.options.prompt.as_deref(),
            self.options.system_prompt.as_deref(),
        );

        write_prompt_file(&prompt_file, &content).await?;

        Ok(Some(prompt_file.to_string_lossy().into_owned()))
    }

    /// Start the agent (non-blocking)
    ///
    /// # Arguments
    /// * `start_options` - Start options
    ///
    /// # Returns
    /// Result indicating success or error
    pub async fn start(&mut self, start_options: AgentStartOptions) -> Result<(), String> {
        if self.options.isolation == "docker" {
            self.options.docker.validate()?;
        }
        // Reject launch options the tool cannot honor before any side effects.
        let capabilities = self
            .options
            .tool_overrides
            .launch_capabilities
            .unwrap_or_else(|| launch_capabilities(&self.options.tool));
        check_launch_options_against(&self.options.tool, &self.options.launch, &capabilities)?;
        let live = self.options.live_input;
        if live && !supports_live_input(&self.options.tool) {
            return Err(live_input_unsupported_error(&self.options.tool));
        }
        let run_timeout = start_options.timeout.or(self.options.timeout);
        isolation::validate_run_timeout(
            run_timeout,
            start_options.close_timeout,
            start_options.detached,
        )?;
        self.close_timeout = start_options.close_timeout;
        if live
            && !start_options.dry_run
            && (start_options.detached || self.options.isolation == "screen")
        {
            return Err("live_input needs an attached run without screen isolation.".to_string());
        }

        // Fail on an invalid environment before any side effects (issue #60).
        let mut child_env = self.child_environment()?;
        if !start_options.dry_run {
            check_gateway_token(self.options.launch.gateway.as_ref(), &child_env)?;
        }

        let model = openai_compatible_gateway::prepare(
            &self.options.tool,
            self.options.launch.gateway.as_ref(),
            self.options.model.as_deref(),
            &mut child_env,
        )?;
        let isolation_target = self.isolation_target(&start_options).await?;

        // Create output stream for JSON parsing if in JSON mode
        if self.options.json || live {
            self.output_stream = Some(create_output_stream());
        }

        // Live input writes the prompt as the first stdin frame instead.
        let prepared_prompt_file = match self
            .prepare_prompt_file(start_options.dry_run || live)
            .await
        {
            Ok(prompt_file) => prompt_file,
            Err(error) => {
                self.cleanup_prompt_temp_dir().await;
                return Err(error);
            }
        };
        let prompt_handled_by_temp_file =
            prepared_prompt_file.is_some() && self.options.prompt_file.is_none();

        // Build the command
        let command_options = AgentCommandOptions {
            tool: self.options.tool.clone(),
            working_directory: self.options.working_directory.clone(),
            prompt: if prompt_handled_by_temp_file || live {
                None
            } else {
                self.options.prompt.clone()
            },
            prompt_file: prepared_prompt_file,
            system_prompt: if prompt_handled_by_temp_file && self.options.tool != "claude" {
                None
            } else {
                self.options.system_prompt.clone()
            },
            append_system_prompt: self.options.append_system_prompt.clone(),
            model,
            fallback_model: self.options.fallback_model.clone(),
            json: self.options.json || live,
            verbose: self.options.verbose,
            replay_user_messages: self.options.replay_user_messages,
            resume: self.options.resume.clone(),
            session_id: self.options.session_id.clone(),
            fork_session: self.options.fork_session,
            read_only: self.options.read_only,
            plan_only: self.options.plan_only,
            approve_each: self.options.approve_each,
            stream_input: live,
            executable: self.options.executable.clone(),
            extra_args: self.options.extra_args.clone(),
            extra_env: self.options.extra_env.clone(),
            unset_env: self.options.unset_env.clone(),
            skip_default_safety_flags: self.options.skip_default_safety_flags,
            isolation: self.options.isolation.clone(),
            screen_name: self.options.screen_name.clone(),
            container_name: self.options.container_name.clone(),
            detached: start_options.detached,
            docker: self.options.docker.clone(),
            docker_tty: start_options.attached
                && !self.options.json
                && std::io::stdout().is_terminal(),
            docker_cid_file: match &isolation_target {
                Some(run_deadline::IsolationTarget::Docker(file)) => Some(file.clone()),
                _ => None,
            },
            docker_env: self
                .options
                .env
                .iter()
                .flatten()
                .map(|(name, _)| name.clone())
                .collect(),
            launch: self.options.launch.clone(),
            overrides: self.options.tool_overrides.clone(),
        };

        let mut command_options = command_options;
        if !start_options.dry_run && self.options.tool_overrides.build_command.is_none() {
            if let Err(error) = self.move_inline_values_to_files(&mut command_options).await {
                self.cleanup_prompt_temp_dir().await;
                return Err(error);
            }
        }
        let command = build_agent_command(&command_options);

        if start_options.dry_run {
            println!("Dry run - command that would be executed:");
            println!("{}", command);
            return Ok(());
        }

        if start_options.detached {
            if let Err(error) = self.start_detached(&command, &child_env).await {
                self.cleanup_prompt_temp_dir().await;
                return Err(error);
            }
        } else {
            // For attached mode, start command without waiting
            let started =
                start_command_with_env(&command, start_options.attached, live, &child_env).await;
            let mut handle = match started.map_err(|e| e.to_string()) {
                Ok(handle) => handle,
                Err(error) => {
                    self.cleanup_prompt_temp_dir().await;
                    return Err(error);
                }
            };
            if let Some(duration) = run_timeout {
                let grace = self.close_timeout.unwrap_or(DEFAULT_KILL_AFTER);
                handle = handle.with_deadline(duration, grace, isolation_target, child_env);
            }
            self.process_handle = Some(handle);
            if live {
                self.write_initial_input_frame().await?;
            }
        }

        Ok(())
    }

    /// Stop the agent and collect output
    ///
    /// # Arguments
    /// * `stop_options` - Stop options
    ///
    /// # Returns
    /// Result with agent output or error
    pub async fn stop(&mut self, stop_options: AgentStopOptions) -> Result<AgentResult, String> {
        let isolation = self.options.isolation.as_str();
        let attached = self.process_handle.is_some();
        let timed = self
            .process_handle
            .as_ref()
            .is_some_and(ProcessHandle::has_deadline);
        if timed {
            isolation::validate_run_timeout(None, stop_options.close_timeout, false)?;
        }
        if matches!(isolation, "screen" | "docker")
            && (stop_options.dry_run || !attached || (isolation == "screen" && !timed))
        {
            return self.stop_isolated(stop_options.dry_run).await;
        }

        if matches!(isolation, "" | "none" | "docker" | "screen") {
            if self.process_handle.is_none() {
                self.cleanup_prompt_temp_dir().await;
                return Err("Agent not started or already stopped".to_string());
            }
            let handle = self
                .process_handle
                .as_mut()
                .ok_or("Agent not started or already stopped")?;
            // End live input: the tool finishes the queued input and exits.
            handle.end_stdin();

            let gateway = self.options.launch.gateway.is_some();
            let close_timeout = stop_options.close_timeout.or(self.close_timeout);
            if let Some(grace) = close_timeout {
                handle.set_deadline_grace(grace);
            }
            let close = ResultCloseOptions {
                close_timeout,
                background_wait: stop_options.background_wait,
                fail_fast_on_auth_error: self.options.fail_fast_on_auth_error.unwrap_or(gateway),
                ..Default::default()
            };
            let outcome = match watch_process_exit(handle, &self.options.tool, close).await {
                Ok(outcome) => outcome,
                Err(error) => {
                    self.cleanup_prompt_temp_dir().await;
                    return Err(error.to_string());
                }
            };
            let exit_code = outcome.exit_code;
            let terminated_after_result =
                outcome.terminated_after_result || stop_options.terminated_after_result;

            let (stdout, stderr, _) = handle.get_output();

            // Combine stdout and stderr for plain output
            let plain_output = if stderr.is_empty() {
                stdout.to_string()
            } else {
                format!("{}\n{}", stdout, stderr)
            };

            // Process output through stream if available
            // A caller's parser replaces the streamed messages too.
            let overrides = &self.options.tool_overrides;
            let mut parsed_output = overrides.parse_output.as_ref().map(|parse| parse(stdout));
            if let (None, Some(stream)) = (&parsed_output, self.output_stream.as_mut()) {
                stream.process(stdout);
                stream.flush();
                let messages = stream.get_messages();
                if !messages.is_empty() {
                    parsed_output = Some(messages.to_vec());
                }
            }

            if parsed_output.is_none() {
                parsed_output = Some(if self.options.tool == "gemini" {
                    tools::gemini::parse_output(stdout)
                } else {
                    streaming::parse_json_records(stdout)
                });
            }

            // Try to extract session ID
            if let Some(extract) = &overrides.extract_session_id {
                self.session_id = extract(stdout);
            } else if is_tool_supported(&self.options.tool) {
                match self.options.tool.as_str() {
                    "claude" => {
                        self.session_id = tools::claude::extract_session_id(stdout);
                    }
                    "codex" => {
                        self.session_id = tools::codex::extract_session_id(stdout);
                    }
                    "opencode" => {
                        self.session_id = tools::opencode::extract_session_id(stdout);
                    }
                    "agent" => {
                        self.session_id = tools::agent::extract_session_id(stdout);
                    }
                    "qwen" => self.session_id = tools::qwen::extract_session_id(stdout),
                    "gemini" => self.session_id = tools::gemini::extract_session_id(stdout),
                    _ => {}
                }
            }

            let usage = match &overrides.extract_usage {
                Some(extract) => extract(stdout),
                None => extract_usage_value(&self.options.tool, stdout),
            };
            let mut metadata = build_normalized_result_metadata(BuildMetadataOptions {
                tool: &self.options.tool,
                exit_code,
                plain_output: &plain_output,
                parsed_output: parsed_output.as_deref(),
                session_id: self.session_id.clone(),
                usage: usage.clone(),
                signal: handle.signal().map(String::from),
                terminated_after_result,
                structured_output_requested: self.options.launch.json_schema.is_some(),
                auth_refusal: outcome.auth_refusal,
            });
            // Codex and Claude can leave a usage limit only in their session
            // files (hive-mind#3570)
            let rollout_options =
                CodexRolloutOptions::for_run_env(&self.options.extra_env, &self.options.unset_env);
            codex_rollout::apply_codex_rollout_usage_limit(&mut metadata, &rollout_options);
            codex_rollout::apply_codex_rollout_usage_windows(&mut metadata, &rollout_options);
            codex_rollout::apply_codex_rollout_context_usage(&mut metadata, &rollout_options);
            if (self.options.json || self.options.tool == "agent")
                && is_tool_supported(&self.options.tool)
            {
                completion::require_completed_result(
                    &mut metadata,
                    &self.options.tool,
                    parsed_output.as_deref().unwrap_or_default(),
                );
            }
            claude_transcript::apply_claude_transcript_usage_limit(
                &mut metadata,
                &ClaudeTranscriptOptions::for_run_env(
                    &self.options.working_directory,
                    &self.options.extra_env,
                    &self.options.unset_env,
                ),
            );

            let exit_code = if handle.timed_out() {
                metadata.success = false;
                metadata.error_during_execution = true;
                metadata.error_type = Some("timeout".into());
                metadata.error_message = Some("The agent exceeded its run deadline.".into());
                metadata.exit_code = None;
                None
            } else {
                Some(exit_code)
            };
            let result = AgentResult {
                exit_code,
                error_type: metadata.error_type.clone(),
                plain_output,
                parsed_output,
                session_id: self.session_id.clone(),
                usage,
                metadata,
            };
            self.cleanup_prompt_temp_dir().await;
            return Ok(result);
        }

        Err(format!(
            "Unsupported isolation mode: {}",
            self.options.isolation
        ))
    }

    /// Cancel a running process and collect its final output and metadata.
    ///
    /// A process cancelled after its final result is judged by that result.
    pub async fn cancel(&mut self) -> Result<AgentResult, String> {
        let mut terminated_after_result = false;
        if matches!(self.options.isolation.as_str(), "docker" | "screen") {
            return self.stop_isolated(false).await;
        }
        if self.options.isolation == "none" || self.options.isolation.is_empty() {
            if let Some(handle) = self.process_handle.as_mut() {
                let mut reader = StdoutMessageReader::new();
                terminated_after_result = !handle.try_wait().map_err(|e| e.to_string())?
                    && has_final_result(&self.options.tool, reader.read(&handle.peek_stdout()));
                handle
                    .terminate()
                    .await
                    .map_err(|error| error.to_string())?;
            }
        }
        self.stop(AgentStopOptions {
            terminated_after_result,
            ..Default::default()
        })
        .await
    }

    /// Get the current session ID (if available)
    pub fn get_session_id(&self) -> Option<&String> {
        self.session_id.as_ref()
    }

    /// Get all collected messages from the output stream
    pub fn get_messages(&self) -> Vec<&Value> {
        if let Some(ref stream) = self.output_stream {
            stream.get_messages().iter().collect()
        } else {
            Vec::new()
        }
    }
}

/// Create an agent controller (convenience function)
///
/// # Arguments
/// * `options` - Agent configuration
///
/// # Returns
/// Result with Agent or error message
pub fn agent(options: AgentOptions) -> Result<Agent, String> {
    Agent::new(options)
}

// Tests are in rust/tests/lib_tests.rs

#[cfg(test)]
mod prompt_dir_tests {
    use super::{create_prompt_temp_dir, write_prompt_file, PROMPT_DIR_SEQUENCE};
    use std::sync::atomic::Ordering;

    #[tokio::test]
    async fn prompt_dirs_are_unique_within_one_clock_tick() {
        let parent = tempfile::tempdir().expect("parent directory");
        let first = create_prompt_temp_dir(parent.path(), 7).await.unwrap();
        let second = create_prompt_temp_dir(parent.path(), 7).await.unwrap();
        assert_ne!(first, second);
        assert!(first.is_dir() && second.is_dir());
    }

    #[tokio::test]
    async fn existing_prompt_dir_names_are_skipped() {
        let parent = tempfile::tempdir().expect("parent directory");
        let next = PROMPT_DIR_SEQUENCE.load(Ordering::Relaxed);
        for sequence in next..next + 3 {
            std::fs::create_dir(parent.path().join(format!(
                "agent-commander-{}-9-{sequence}",
                std::process::id()
            )))
            .unwrap();
        }
        let dir = create_prompt_temp_dir(parent.path(), 9).await.unwrap();
        assert!(dir.is_dir());
        assert_eq!(std::fs::read_dir(parent.path()).unwrap().count(), 4);
    }

    /// A tokio `File` writes at most 2 MiB per background operation, so a
    /// larger prompt must be complete before the agent is spawned to read it.
    #[tokio::test]
    async fn large_prompt_files_are_complete_when_written() {
        let parent = tempfile::tempdir().expect("parent directory");
        let content = "x".repeat(3 * 1024 * 1024 + 37);
        for attempt in 0..20 {
            let path = parent.path().join(format!("prompt-{attempt}.txt"));
            write_prompt_file(&path, &content).await.unwrap();
            assert_eq!(
                std::fs::metadata(&path).unwrap().len(),
                content.len() as u64,
                "attempt {attempt}"
            );
        }
    }
}