agent-exec 0.1.18

Non-interactive agent job runner. Runs commands as background jobs and returns structured JSON on stdout.
Documentation
//! Implementation of the `wait` sub-command.
//!
//! Polls `state.json` until the job leaves the `running` state or a timeout
//! is reached.

use anyhow::Result;
use tracing::debug;

use crate::jobstore::{JobDir, resolve_root};
use crate::schema::{Response, WaitData};

/// Options for the `wait` sub-command.
#[derive(Debug)]
pub struct WaitOpts<'a> {
    pub job_id: &'a str,
    pub root: Option<&'a str>,
    /// Poll interval in milliseconds.
    pub poll_ms: u64,
    /// Total timeout in milliseconds (default 30000).
    /// Ignored when `forever` is true.
    pub until: u64,
    /// Wait indefinitely when true.
    pub forever: bool,
}

impl<'a> Default for WaitOpts<'a> {
    fn default() -> Self {
        WaitOpts {
            job_id: "",
            root: None,
            poll_ms: 200,
            until: 30_000,
            forever: false,
        }
    }
}

/// Execute `wait`: poll until done, then emit JSON.
pub fn execute(opts: WaitOpts) -> Result<()> {
    let root = resolve_root(opts.root);
    let job_dir = JobDir::open(&root, opts.job_id)?;

    let poll = std::time::Duration::from_millis(opts.poll_ms);
    let deadline = if opts.forever {
        None
    } else {
        Some(std::time::Instant::now() + std::time::Duration::from_millis(opts.until))
    };

    loop {
        let state = job_dir.read_state()?;
        debug!(job_id = %opts.job_id, state = ?state.status(), "wait poll");

        if !state.status().is_non_terminal() {
            let response = Response::new(
                "wait",
                WaitData {
                    job_id: job_dir.job_id.clone(),
                    state: state.status().as_str().to_string(),
                    exit_code: state.exit_code(),
                },
            );
            response.print();
            return Ok(());
        }

        if let Some(dl) = deadline
            && std::time::Instant::now() >= dl
        {
            // Timed out — still in a non-terminal state (created or running).
            let response = Response::new(
                "wait",
                WaitData {
                    job_id: job_dir.job_id.clone(),
                    state: state.status().as_str().to_string(),
                    exit_code: None,
                },
            );
            response.print();
            return Ok(());
        }

        std::thread::sleep(poll);
    }
}