iron-core 0.1.35

Core AgentIron loop, session state, and tool registry
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
//! Command-line interface for the `agent-iron` headless binary.
//!
//! The CLI is run-only: `agent-iron run <task-id>` executes an existing
//! automation task non-interactively. All task/prompt/profile management is
//! handled by the GUI and typed core APIs.
//!
//! ## Precedence
//!
//! Command-line values take precedence over `AGENTIRON_*` environment
//! variables, which take precedence over documented defaults. The task ID is
//! always a positional argument and is never sourced from an environment
//! variable.
//!
//! ## Exit codes
//!
//! | Code | Meaning                       |
//! |------|-------------------------------|
//! | 0    | completed                     |
//! | 2    | usage error                   |
//! | 3    | configuration or reference    |
//! | 4    | unsafe policy                 |
//! | 5    | provider/credential init      |
//! | 6    | execution failure             |
//! | 7    | cancelled                     |
//! | 8    | timed out                     |

use crate::config::{default_config_path, ConfigStore};
use crate::execution::{AutomationRunErrorCategory, AutomationRunResult, AutomationRunStatus};
use crate::headless::{bootstrap_headless, run_automation, HeadlessBootstrapError};
use std::io::Write;
use std::path::PathBuf;
use std::time::Duration;
use tokio_util::sync::CancellationToken;

// ============================================================================
// Exit codes
// ============================================================================

pub const EXIT_COMPLETED: i32 = 0;
pub const EXIT_USAGE: i32 = 2;
pub const EXIT_CONFIG: i32 = 3;
pub const EXIT_UNSAFE_POLICY: i32 = 4;
pub const EXIT_PROVIDER_INIT: i32 = 5;
pub const EXIT_EXECUTION: i32 = 6;
pub const EXIT_CANCELLED: i32 = 7;
pub const EXIT_TIMED_OUT: i32 = 8;

// ============================================================================
// Output format
// ============================================================================

/// Output format selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    Text,
    Json,
}

// ============================================================================
// Parsed arguments
// ============================================================================

/// Parsed CLI arguments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliArgs {
    pub task_id: String,
    pub config: Option<String>,
    pub workspace: Option<String>,
    pub timeout: Option<String>,
    pub format: Option<String>,
    pub quiet: bool,
}

/// Usage error from argument parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UsageError {
    pub message: String,
}

impl std::fmt::Display for UsageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for UsageError {}

const USAGE: &str = "\
Usage: agent-iron run <task-id> [OPTIONS]

Options:
  -c, --config <path>     Path to ConfigStore database
  --workspace <dir>       Workspace directory (default: process cwd)
  --timeout <duration>    Execution timeout (e.g. 30s, 5m, 1h) [required]
  -o, --format <text|json> Output format (default: text)
  -q, --quiet             Suppress progress output on stderr
  -h, --help              Show this help message";

/// Parse command-line arguments (everything after the program name).
pub fn parse_args(args: &[String]) -> Result<CliArgs, UsageError> {
    if args.is_empty() {
        return Err(UsageError {
            message: format!("missing 'run' subcommand\n\n{}", USAGE),
        });
    }

    let subcommand = args[0].as_str();
    if subcommand == "-h" || subcommand == "--help" {
        return Err(UsageError {
            message: USAGE.to_string(),
        });
    }
    if subcommand != "run" {
        return Err(UsageError {
            message: format!(
                "unknown subcommand '{}': only 'run' is supported\n\n{}",
                subcommand, USAGE
            ),
        });
    }

    let mut task_id: Option<String> = None;
    let mut config: Option<String> = None;
    let mut workspace: Option<String> = None;
    let mut timeout: Option<String> = None;
    let mut format: Option<String> = None;
    let mut quiet = false;

    let rest = &args[1..];
    let mut i = 0;
    while i < rest.len() {
        let arg = &rest[i];
        match arg.as_str() {
            "--config" | "-c" => {
                i += 1;
                config = Some(expect_value(rest, i, "--config")?);
            }
            "--workspace" => {
                i += 1;
                workspace = Some(expect_value(rest, i, "--workspace")?);
            }
            "--timeout" => {
                i += 1;
                timeout = Some(expect_value(rest, i, "--timeout")?);
            }
            "--format" | "-o" => {
                i += 1;
                format = Some(expect_value(rest, i, "--format")?);
            }
            "--quiet" | "-q" => {
                quiet = true;
            }
            "-h" | "--help" => {
                return Err(UsageError {
                    message: USAGE.to_string(),
                });
            }
            s if s.starts_with('-') => {
                return Err(UsageError {
                    message: format!("unknown option '{}'\n\n{}", s, USAGE),
                });
            }
            s => {
                if task_id.is_none() {
                    task_id = Some(s.to_string());
                } else {
                    return Err(UsageError {
                        message: format!("unexpected positional argument '{}'\n\n{}", s, USAGE),
                    });
                }
            }
        }
        i += 1;
    }

    let task_id = task_id.ok_or_else(|| UsageError {
        message: format!(
            "missing required <task-id> positional argument\n\n{}",
            USAGE
        ),
    })?;

    Ok(CliArgs {
        task_id,
        config,
        workspace,
        timeout,
        format,
        quiet,
    })
}

fn expect_value(args: &[String], idx: usize, flag: &str) -> Result<String, UsageError> {
    args.get(idx).cloned().ok_or_else(|| UsageError {
        message: format!("{} requires a value\n\n{}", flag, USAGE),
    })
}

/// Lightweight raw scan of args to detect a JSON output request
/// (`--format json`, `-o json`, or `--format=json`) without a full parse.
///
/// Used to honor the JSON output contract for usage errors that occur before
/// argument parsing completes.
fn raw_args_request_json(args: &[String]) -> bool {
    let mut i = 0;
    while i < args.len() {
        let a = args[i].as_str();
        if a == "--format" || a == "-o" {
            if let Some(v) = args.get(i + 1) {
                if v.trim().eq_ignore_ascii_case("json") {
                    return true;
                }
            }
            i += 2;
            continue;
        }
        if let Some(v) = a.strip_prefix("--format=") {
            if v.trim().eq_ignore_ascii_case("json") {
                return true;
            }
        }
        i += 1;
    }
    false
}

// ============================================================================
// Duration parsing
// ============================================================================

/// Parse a positive duration string like `30s`, `5m`, `1h`.
///
/// Returns an error for zero, negative, or malformed values.
pub fn parse_duration(s: &str) -> Result<Duration, String> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err("timeout must not be empty".to_string());
    }

    let last = trimmed.chars().last().unwrap();
    let (num_str, multiplier) = match last {
        's' => (&trimmed[..trimmed.len() - 1], 1u64),
        'm' => (&trimmed[..trimmed.len() - 1], 60),
        'h' => (&trimmed[..trimmed.len() - 1], 3600),
        c if c.is_ascii_digit() => (trimmed, 1u64),
        _ => {
            return Err(format!(
                "invalid timeout unit '{}': use 30s, 5m, or 1h",
                last
            ))
        }
    };

    let seconds: u64 = num_str.parse().map_err(|_| {
        format!(
            "invalid timeout value '{}': expected a positive number",
            num_str
        )
    })?;

    if seconds == 0 {
        return Err("timeout must be greater than zero".to_string());
    }

    let total = seconds
        .checked_mul(multiplier)
        .ok_or_else(|| "timeout value is too large".to_string())?;

    Ok(Duration::from_secs(total))
}

// ============================================================================
// Resolution functions (CLI > env > defaults)
// ============================================================================

/// Resolve workspace from CLI, environment, or task fallback.
///
/// Canonicalizes the path and requires it to be an existing directory.
pub fn resolve_workspace(
    cli: Option<&str>,
    env: Option<&str>,
    fallback: Option<&std::path::Path>,
) -> Result<PathBuf, String> {
    let path = match cli.or(env) {
        Some(raw) => PathBuf::from(raw),
        None => match fallback {
            Some(p) => p.to_path_buf(),
            None => {
                return Err(
                    "workspace is required: use --workspace, AGENTIRON_WORKSPACE, \
                     or set a project root on the automation task"
                        .to_string(),
                )
            }
        },
    };

    if !path.exists() {
        return Err(format!("workspace does not exist: {}", path.display()));
    }
    if !path.is_dir() {
        return Err(format!("workspace is not a directory: {}", path.display()));
    }

    path.canonicalize().map_err(|e| {
        format!(
            "failed to canonicalize workspace '{}': {}",
            path.display(),
            e
        )
    })
}

/// Resolve the ConfigStore database path from CLI, environment, or default.
pub fn resolve_config_path(cli: Option<&str>, env: Option<&str>) -> Result<PathBuf, String> {
    if let Some(p) = cli {
        return Ok(PathBuf::from(p));
    }
    if let Some(p) = env {
        return Ok(PathBuf::from(p));
    }
    default_config_path().map_err(|e| format!("failed to determine default config path: {}", e))
}

/// Resolve timeout duration from CLI, environment, or task fallback.
pub fn resolve_timeout(
    cli: Option<&str>,
    env: Option<&str>,
    fallback: Option<Duration>,
) -> Result<Duration, String> {
    if let Some(raw) = cli.or(env) {
        return parse_duration(raw);
    }

    fallback.ok_or_else(|| {
        "timeout is required: use --timeout, AGENTIRON_TIMEOUT, \
         or set a timeout on the automation task"
            .to_string()
    })
}

/// Resolve output format from CLI or environment (default: text).
pub fn resolve_format(cli: Option<&str>, env: Option<&str>) -> Result<OutputFormat, String> {
    let raw = cli.or(env).unwrap_or("text");
    match raw.trim().to_lowercase().as_str() {
        "text" => Ok(OutputFormat::Text),
        "json" => Ok(OutputFormat::Json),
        other => Err(format!(
            "invalid format '{}': expected 'text' or 'json'",
            other
        )),
    }
}

/// Resolve quiet flag from CLI flag or environment.
pub fn resolve_quiet(quiet_flag: bool, env: Option<&str>) -> bool {
    if quiet_flag {
        return true;
    }
    matches!(
        env.map(|s| s.trim().to_lowercase()),
        Some(ref s) if s == "1" || s == "true" || s == "yes"
    )
}

// ============================================================================
// Exit-code mapping
// ============================================================================

/// Map a terminal run status to the stable exit code.
pub fn exit_code_for_status(status: AutomationRunStatus) -> i32 {
    match status {
        AutomationRunStatus::Completed => EXIT_COMPLETED,
        AutomationRunStatus::Failed => EXIT_EXECUTION,
        AutomationRunStatus::Cancelled => EXIT_CANCELLED,
        AutomationRunStatus::TimedOut => EXIT_TIMED_OUT,
    }
}

/// Map a run result to the stable exit code, considering the error category
/// for failed runs.
pub fn exit_code_for_result(result: &AutomationRunResult) -> i32 {
    match result.status {
        AutomationRunStatus::Completed => EXIT_COMPLETED,
        AutomationRunStatus::Cancelled => EXIT_CANCELLED,
        AutomationRunStatus::TimedOut => EXIT_TIMED_OUT,
        AutomationRunStatus::Failed => match result.error.as_ref().map(|e| &e.category) {
            Some(AutomationRunErrorCategory::Config)
            | Some(AutomationRunErrorCategory::Reference) => EXIT_CONFIG,
            Some(AutomationRunErrorCategory::UnsafePolicy) => EXIT_UNSAFE_POLICY,
            Some(AutomationRunErrorCategory::ProviderInit) => EXIT_PROVIDER_INIT,
            _ => EXIT_EXECUTION,
        },
    }
}

/// Map a bootstrap error to the stable exit code.
pub fn exit_code_for_bootstrap_error(err: &HeadlessBootstrapError) -> i32 {
    match err {
        HeadlessBootstrapError::MissingDefaultProvider
        | HeadlessBootstrapError::ProviderInit { .. }
        | HeadlessBootstrapError::CredentialFailure { .. }
        | HeadlessBootstrapError::InteractiveAuthRequired { .. } => EXIT_PROVIDER_INIT,
        HeadlessBootstrapError::UnsafePolicy(_) | HeadlessBootstrapError::UnavailableTool(_) => {
            EXIT_UNSAFE_POLICY
        }
        HeadlessBootstrapError::Config(_) | HeadlessBootstrapError::Resolution(_) => EXIT_CONFIG,
    }
}

// ============================================================================
// Bootstrap-error to result mapping (for JSON failure output)
// =============================================================================

/// Convert a bootstrap error into an `AutomationRunErrorCategory`.
fn bootstrap_error_category(err: &HeadlessBootstrapError) -> AutomationRunErrorCategory {
    match err {
        HeadlessBootstrapError::MissingDefaultProvider
        | HeadlessBootstrapError::ProviderInit { .. }
        | HeadlessBootstrapError::CredentialFailure { .. }
        | HeadlessBootstrapError::InteractiveAuthRequired { .. } => {
            AutomationRunErrorCategory::ProviderInit
        }
        HeadlessBootstrapError::UnsafePolicy(_) | HeadlessBootstrapError::UnavailableTool(_) => {
            AutomationRunErrorCategory::UnsafePolicy
        }
        HeadlessBootstrapError::Config(_) | HeadlessBootstrapError::Resolution(_) => {
            AutomationRunErrorCategory::Config
        }
    }
}

// ============================================================================
// Output formatting
// ============================================================================

/// Format a run result for text-mode stdout (final assistant text only).
pub fn format_text_output(result: &AutomationRunResult) -> String {
    result.output.clone()
}

/// Format a run result as a single versioned JSON object.
pub fn format_json_output(result: &AutomationRunResult) -> String {
    serde_json::to_string_pretty(result).unwrap_or_else(|e| {
        format!(
            "{{\"schema_version\":1,\"status\":\"failed\",\"error\":{{\"category\":\"execution\",\"message\":\"failed to serialize result: {}\"}}}}",
            e
        )
    })
}

// ============================================================================
// Signal handling
// ============================================================================

/// Wait for an interrupt (SIGINT) or termination (SIGTERM) signal.
async fn wait_for_signal() {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{signal, SignalKind};
        let sigterm = signal(SignalKind::terminate());
        let mut sigterm = match sigterm {
            Ok(s) => s,
            Err(_) => {
                let _ = tokio::signal::ctrl_c().await;
                return;
            }
        };
        tokio::select! {
            _ = tokio::signal::ctrl_c() => {}
            _ = sigterm.recv() => {}
        }
    }
    #[cfg(not(unix))]
    {
        let _ = tokio::signal::ctrl_c().await;
    }
}

// ============================================================================
// Main execution entry point
// ============================================================================

/// Execute a headless automation run end-to-end.
///
/// Returns the process exit code. This function is intended to be called
/// from the binary's `main` on a `current_thread` Tokio runtime inside a
/// `LocalSet`.
pub async fn execute_run(args: &[String]) -> i32 {
    let env: Vec<(String, String)> = std::env::vars().collect();
    execute_run_with_streams(
        args,
        &mut env.clone(),
        &mut std::io::stdout(),
        &mut std::io::stderr(),
    )
    .await
}

/// Execute a headless run using the provided environment variables.
///
/// Separated from [`execute_run`] for testability.
pub async fn execute_run_with_env(args: &[String], env: &mut [(String, String)]) -> i32 {
    execute_run_with_streams(args, env, &mut std::io::stdout(), &mut std::io::stderr()).await
}

/// Execute a headless run writing output to the provided writers.
///
/// This is the core implementation. Tests pass `Vec<u8>` buffers to capture
/// stdout and stderr.
pub async fn execute_run_with_streams(
    args: &[String],
    env: &mut [(String, String)],
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> i32 {
    // Detect JSON output mode from raw args/env so that usage errors emitted
    // before or during argument parsing still honor the JSON output contract.
    let json_mode = raw_args_request_json(args)
        || env_get(env, "AGENTIRON_FORMAT")
            .map(|v| v.trim().eq_ignore_ascii_case("json"))
            .unwrap_or(false);

    // 1. Parse arguments.
    let parsed = match parse_args(args) {
        Ok(p) => p,
        Err(e) => {
            if json_mode {
                let result = AutomationRunResult::cli_failure(
                    "unknown",
                    PathBuf::from("."),
                    AutomationRunErrorCategory::Config,
                    e.message.clone(),
                );
                let _ = writeln!(stdout, "{}", format_json_output(&result));
            } else {
                let _ = writeln!(stderr, "{}", e.message);
            }
            return EXIT_USAGE;
        }
    };

    // 2. Resolve output format early to know if JSON mode is active.
    let format = match resolve_format(parsed.format.as_deref(), env_get(env, "AGENTIRON_FORMAT")) {
        Ok(f) => f,
        Err(e) => {
            let _ = writeln!(stderr, "{}", e);
            return EXIT_USAGE;
        }
    };

    let quiet = resolve_quiet(parsed.quiet, env_get(env, "AGENTIRON_QUIET"));

    // Helper: emit a failure and return an exit code.
    // In JSON mode, constructs a terminal JSON object on stdout.
    // In text mode, writes the error to stderr.
    macro_rules! emit_failure {
        ($category:expr, $message:expr, $exit_code:expr, $workspace:expr) => {{
            match format {
                OutputFormat::Json => {
                    let result = AutomationRunResult::cli_failure(
                        &parsed.task_id,
                        $workspace,
                        $category,
                        $message,
                    );
                    let _ = writeln!(stdout, "{}", format_json_output(&result));
                }
                OutputFormat::Text => {
                    let _ = writeln!(stderr, "{}", &$message);
                }
            }
            return $exit_code;
        }};
    }

    // 3. Resolve config path and open ConfigStore (moved before
    //    workspace/timeout so we can load task defaults).
    let config_path =
        match resolve_config_path(parsed.config.as_deref(), env_get(env, "AGENTIRON_CONFIG")) {
            Ok(p) => p,
            Err(e) => {
                emit_failure!(
                    AutomationRunErrorCategory::Config,
                    e,
                    EXIT_CONFIG,
                    PathBuf::from(parsed.workspace.as_deref().unwrap_or("."))
                );
            }
        };

    if !quiet {
        let _ = writeln!(stderr, "config: {}", config_path.display());
    }

    let store = match ConfigStore::open_at(&config_path).await {
        Ok(s) => s,
        Err(e) => {
            emit_failure!(
                AutomationRunErrorCategory::Config,
                format!("failed to open config store: {}", e),
                EXIT_CONFIG,
                PathBuf::from(parsed.workspace.as_deref().unwrap_or("."))
            );
        }
    };

    // 4. Load the task to get workspace/timeout defaults.
    let task_defaults = match store.get_automation_task(&parsed.task_id).await {
        Ok(Some(t)) => Some(t),
        Ok(None) => None,
        Err(e) => {
            emit_failure!(
                AutomationRunErrorCategory::Config,
                format!("failed to load task '{}': {}", parsed.task_id, e),
                EXIT_CONFIG,
                PathBuf::from(parsed.workspace.as_deref().unwrap_or("."))
            );
        }
    };

    let workspace_fallback = task_defaults
        .as_ref()
        .filter(|t| !t.project_root.as_os_str().is_empty())
        .map(|t| t.project_root.as_path());

    let timeout_fallback = task_defaults
        .as_ref()
        .filter(|t| t.timeout_seconds > 0)
        .map(|t| Duration::from_secs(t.timeout_seconds));

    // 5. Resolve workspace (CLI > env > task project root).
    let workspace = match resolve_workspace(
        parsed.workspace.as_deref(),
        env_get(env, "AGENTIRON_WORKSPACE"),
        workspace_fallback,
    ) {
        Ok(w) => w,
        Err(e) => {
            emit_failure!(
                AutomationRunErrorCategory::Config,
                e,
                EXIT_CONFIG,
                PathBuf::from(parsed.workspace.as_deref().unwrap_or("."))
            );
        }
    };

    if !quiet {
        let _ = writeln!(stderr, "workspace: {}", workspace.display());
    }

    // 6. Resolve timeout (CLI > env > task timeout).
    let timeout = match resolve_timeout(
        parsed.timeout.as_deref(),
        env_get(env, "AGENTIRON_TIMEOUT"),
        timeout_fallback,
    ) {
        Ok(t) => t,
        Err(e) => {
            emit_failure!(AutomationRunErrorCategory::Config, e, EXIT_USAGE, workspace);
        }
    };

    if !quiet {
        let _ = writeln!(stderr, "timeout: {:?}", timeout);
    }

    // 6. Bootstrap headless runtime.
    if !quiet {
        let _ = writeln!(stderr, "bootstrapping headless runtime...");
    }

    let headless =
        match bootstrap_headless(store, &parsed.task_id, workspace.clone(), timeout).await {
            Ok(h) => h,
            Err(e) => {
                let code = exit_code_for_bootstrap_error(&e);
                emit_failure!(bootstrap_error_category(&e), e.to_string(), code, workspace);
            }
        };

    if !quiet {
        let _ = writeln!(
            stderr,
            "running task '{}' with provider '{}' model '{}'",
            parsed.task_id, headless.provider_slug, headless.model
        );
    }

    // 7. Set up signal handler.
    let cancel = CancellationToken::new();
    let signal_cancel = cancel.clone();
    tokio::spawn(async move {
        wait_for_signal().await;
        signal_cancel.cancel();
    });

    // 8. Execute the automation run.
    let result = run_automation(headless, timeout, cancel).await;

    // 9. Format and emit output.
    match format {
        OutputFormat::Text => {
            let text = format_text_output(&result);
            let _ = writeln!(stdout, "{}", text);
        }
        OutputFormat::Json => {
            let json = format_json_output(&result);
            let _ = writeln!(stdout, "{}", json);
        }
    }

    exit_code_for_result(&result)
}

/// Look up an environment variable from a collected vector.
fn env_get<'a>(env: &'a [(String, String)], key: &str) -> Option<&'a str> {
    env.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests;