Skip to main content

blyte_cli/
task_runner.rs

1//! Headless single-shot solver runner for executing direct agent prompts.
2//!
3//! Wires together the configured LLM provider, execution shell (local host or container sandbox),
4//! filesystem abstraction, context strategy, and verification gate runner into an autonomous loop.
5
6use std::io::Write;
7use std::path::PathBuf;
8use std::sync::{Arc, Mutex};
9
10/// Tracks turn and gate progress across the run, for the deadline watchdog.
11#[derive(Debug, Default, Clone, Copy)]
12pub struct Progress {
13    pub turns: u32,
14    pub gate_attempts: u32,
15    pub in_gate: bool,
16    pub gate_wait_ms: u64,
17}
18
19/// Execution parameters for running an autonomous solver task to completion.
20#[derive(Debug, Clone)]
21pub struct TaskConfig {
22    /// Goal or task prompt for the agent to resolve.
23    pub prompt: String,
24    /// Optional command string executed to determine task success (exit 0).
25    pub gate: Option<String>,
26    pub context_strategy: String,
27    /// Model identifier override passed to the provider.
28    pub model: Option<String>,
29    /// Container identifier if execution is sandboxed inside a Docker container.
30    pub container: Option<String>,
31    /// Maximum allowed turn iterations before exhausting budget.
32    pub max_turns: usize,
33    /// Maximum verification gate retry attempts.
34    pub max_gates: usize,
35    /// Whether to roll back working tree on gate failure.
36    pub rollback: bool,
37    /// Target repository or workspace root on the local filesystem.
38    pub root: PathBuf,
39    /// Working directory inside the container (`--container-workdir`).
40    pub container_workdir: String,
41    /// Wall-clock budget in seconds (`--max-seconds`).
42    pub max_seconds: Option<u64>,
43    /// Maximum spend in USD (`--max-cost`).
44    pub max_cost_usd: Option<f64>,
45    /// Where to write the JSON run report, if anywhere (`--report`).
46    pub report: Option<PathBuf>,
47    /// Fold budget in approximate tokens (`--fold-budget`).
48    pub fold_budget: Option<usize>,
49    /// Sandbox local command execution mode (`--sandbox`).
50    pub sandbox: String,
51    /// Network outbound mode for commands (`--network`).
52    pub network: String,
53    /// Paths permitted for reading despite credential deny-list (`--allow-read`).
54    pub allow_read: Vec<PathBuf>,
55    /// Environment variables permitted to pass to commands despite looking like credentials (`--pass-env`).
56    pub pass_env: Vec<String>,
57    /// Whether this is a research run: periodically remind the model to keep report.md updated.
58    pub research: bool,
59}
60
61impl From<&crate::cli::Cli> for TaskConfig {
62    /// Maps parsed CLI flags into a concrete `TaskConfig` configuration.
63    fn from(cli: &crate::cli::Cli) -> Self {
64        blyte_agent::tools::set_read_roots(cli.read_roots.clone());
65        // Fall back to current working directory if not running in container mode
66        let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
67
68        Self {
69            prompt: cli.prompt.clone().unwrap_or_default(),
70            gate: cli.gate.clone(),
71            context_strategy: cli.context.clone(),
72            model: cli.model.clone(),
73            container: cli.container.clone(),
74            max_turns: cli.max_turns,
75            max_gates: cli.max_gates,
76            rollback: cli.rollback,
77            root,
78            container_workdir: cli.container_workdir.clone(),
79            max_seconds: cli.max_seconds,
80            max_cost_usd: cli.max_cost_usd,
81            report: cli.report.clone(),
82            fold_budget: cli.fold_budget,
83            sandbox: cli.sandbox.clone(),
84            network: cli.network.clone(),
85            allow_read: cli.allow_read.clone(),
86            pass_env: cli.pass_env.clone(),
87            research: cli.research,
88        }
89    }
90}
91
92/// Validates network configuration against the environment and active flags.
93///
94/// Refuses `--network=off` when running with `--container`, when `--sandbox=off`,
95/// when the sandbox is unavailable, or on Linux when `landlock_abi() < 4`.
96pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
97    if config.network == "off" {
98        if config.container.is_some() {
99            return Err(
100                "--network=off is not supported with --container; set the container's network instead"
101                    .into(),
102            );
103        }
104        if config.sandbox != "on" {
105            return Err("--network=off needs the sandbox".into());
106        }
107        #[cfg(target_os = "linux")]
108        if blyte_agent::sandbox::landlock_abi() < 4 {
109            return Err("--network=off on Linux needs Linux 6.7 or later".into());
110        }
111        if !blyte_agent::sandbox::available() {
112            return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
113        }
114    }
115    Ok(())
116}
117
118/// Executes an autonomous solver run using the provided task configuration and live stdout.
119///
120/// Configures the AI provider, context strategy, execution environment (local or container),
121/// and deterministic gate loop, printing live event progress as turns execute.
122///
123/// # Arguments
124///
125/// * `config` - Parameters governing prompt, budgets, gate verification, and environment.
126///
127/// # Returns
128///
129/// Returns `Ok((Outcome, RunReport))` containing final completion status and metrics,
130/// or an `Err(String)` describing initialization failure.
131pub fn run_task(
132    config: TaskConfig,
133) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
134    let started = std::time::Instant::now();
135    let progress = Arc::new(Mutex::new(Progress::default()));
136    if let Some(s) = config.max_seconds {
137        // BLYTE_WATCHDOG_GRACE_SECS exists for tests.
138        let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
139            .ok()
140            .and_then(|v| v.trim().parse().ok())
141            .unwrap_or(30);
142        let watchdog_config = config.clone();
143        let watchdog_progress = Arc::clone(&progress);
144        std::thread::spawn(move || {
145            loop {
146                let wait_ms = match watchdog_progress.lock() {
147                    Ok(g) => g.gate_wait_ms,
148                    Err(e) => e.into_inner().gate_wait_ms,
149                };
150                let deadline = started
151                    + std::time::Duration::from_secs(s.saturating_add(grace_secs))
152                    + std::time::Duration::from_millis(wait_ms);
153                match deadline.checked_duration_since(std::time::Instant::now()) {
154                    Some(remaining) if !remaining.is_zero() => {
155                        std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
156                    }
157                    _ => break,
158                }
159            }
160            let p = match watchdog_progress.lock() {
161                Ok(g) => *g,
162                Err(e) => *e.into_inner(),
163            };
164            let msg = if p.in_gate {
165                format!(
166                    "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
167                    p.gate_attempts
168                )
169            } else {
170                format!(
171                    "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
172                    p.turns
173                )
174            };
175            if let Some(path) = &watchdog_config.report {
176                let mut record =
177                    crate::report::RunRecord::from_error(&watchdog_config, &msg, started.elapsed());
178                record.turns = p.turns;
179                record.gate_attempts = p.gate_attempts;
180                let _ = crate::report::write(path, &record);
181            }
182            eprintln!("blyte: {msg}");
183            std::process::exit(1);
184        });
185    }
186    let verification_cmd = config.gate.as_deref().unwrap_or("");
187    let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
188    state.orchestrator.max_cost_usd = config.max_cost_usd;
189    let mut stdout = std::io::stdout();
190    let result =
191        run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
192    // The loop writes its own report; this covers a run that never reached it (e.g. no API
193    // key), so a caller always finds one. An absent report would read as a crash.
194    if let (Err(e), Some(path)) = (&result, &config.report) {
195        crate::report::write(
196            path,
197            &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
198        )?;
199    }
200    result
201}
202
203/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`.
204///
205/// Preserves session mutations (epistemic ledger, patches, attempts) directly in the provided `state`.
206///
207/// # Arguments
208///
209/// * `config` - Execution parameters.
210/// * `state` - The mutable session state to advance.
211/// * `writer` - Stream writer sink for formatted events.
212///
213/// # Returns
214///
215/// Returns `Ok((Outcome, RunReport))` or an `Err(String)` describing failure.
216pub fn run_task_with_state_and_writer<W: Write>(
217    config: &TaskConfig,
218    state: &mut blyte_agent::state::State,
219    writer: &mut W,
220) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
221    let progress = Arc::new(Mutex::new(Progress::default()));
222    run_task_with_state_writer_and_progress(config, state, writer, progress)
223}
224
225/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
226/// and updating the shared `progress` record.
227pub fn run_task_with_state_writer_and_progress<W: Write>(
228    config: &TaskConfig,
229    state: &mut blyte_agent::state::State,
230    writer: &mut W,
231    progress: Arc<Mutex<Progress>>,
232) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
233    check_network_mode(config)?;
234    let started = std::time::Instant::now();
235    // 1. Initialize LLM provider from environment credentials or model specification.
236    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
237    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
238        Ok(p) => p,
239        Err(blyte_provider::ProviderError::MissingKey(key)) => {
240            return Err(format!(
241                "Provider error: no API key: set {key} in environment"
242            ));
243        }
244        Err(e) => return Err(format!("Provider error: {e}")),
245    };
246
247    let model_id = provider.model_id();
248    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
249        return Err(format!(
250            "--max-cost needs a known price for {model_id}; none is known"
251        ));
252    }
253    state.orchestrator.max_cost_usd = config.max_cost_usd;
254
255    // 2. Select context assembly strategy.
256    let folded = blyte_agent::context::Folded {
257        budget_tokens: config
258            .fold_budget
259            .unwrap_or(blyte_agent::context::Folded::default().budget_tokens),
260    };
261    let conversational = blyte_agent::context::Conversational;
262    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
263        match config.context_strategy.as_str() {
264            "conversational" => &conversational,
265            _ => &folded,
266        };
267
268    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
269    // and `export` carry over). Container files go through a session too. Each falls back to a
270    // process per command if a session cannot start.
271    let local_fs = blyte_agent::fs::LocalFs;
272    let (persistent, session_fs, root) = match &config.container {
273        Some(cid) => (
274            blyte_agent::shell::PersistentShell::container(
275                cid.clone(),
276                PathBuf::from(&config.container_workdir),
277            ),
278            Some(blyte_agent::fs::SessionFs::container(
279                cid.clone(),
280                PathBuf::from(&config.container_workdir),
281            )),
282            PathBuf::from(&config.container_workdir),
283        ),
284        None => {
285            blyte_agent::shell::set_pass_env(config.pass_env.clone());
286            if let Some(r) = blyte_agent::rules::load(&config.root) {
287                eprintln!("blyte: repository rules from {}", r.source.display());
288            }
289            let withheld = blyte_agent::shell::withheld_env();
290            if !withheld.is_empty() {
291                eprintln!(
292                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
293                    withheld.join(", ")
294                );
295            }
296            let shell = if config.sandbox == "on" {
297                if blyte_agent::sandbox::available() {
298                    let profile = blyte_agent::sandbox::default_profile_net(
299                        &config.root,
300                        &config.allow_read,
301                        config.network == "on",
302                    );
303                    if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
304                        eprintln!(
305                            "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
306                        );
307                    }
308                    if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
309                        eprintln!(
310                            "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
311                        );
312                    }
313                    if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } =
314                        &profile
315                    {
316                        eprintln!(
317                            "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
318                        );
319                        if *block_tcp {
320                            eprintln!(
321                                "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
322                            );
323                        }
324                    }
325                    blyte_agent::shell::PersistentShell::local_sandboxed(
326                        config.root.clone(),
327                        profile,
328                    )
329                } else {
330                    eprintln!("warning: sandbox unavailable; running unsandboxed");
331                    blyte_agent::shell::PersistentShell::local(config.root.clone())
332                }
333            } else {
334                blyte_agent::shell::PersistentShell::local(config.root.clone())
335            };
336            (shell, None, config.root.clone())
337        }
338    };
339    let shell: &dyn blyte_agent::shell::Shell = &persistent;
340    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
341        Some(f) => f,
342        None => &local_fs,
343    };
344
345    // 4. Wrap writer in a Mutex so the event callback satisfies Fn trait bounds.
346    let writer_mutex = Mutex::new(writer);
347    let on_event = |event: blyte_agent::run::Event<'_>| {
348        {
349            let mut p = match progress.lock() {
350                Ok(g) => g,
351                Err(e) => e.into_inner(),
352            };
353            match &event {
354                blyte_agent::run::Event::Turn { n, .. } => {
355                    p.turns = *n;
356                    p.in_gate = false;
357                }
358                blyte_agent::run::Event::GateStart { attempt } => {
359                    p.gate_attempts = *attempt;
360                    p.in_gate = true;
361                }
362                blyte_agent::run::Event::GateSlotWait { ms } => {
363                    p.gate_wait_ms += ms;
364                }
365                blyte_agent::run::Event::Gate { .. } => {
366                    p.in_gate = false;
367                }
368                _ => {}
369            }
370        }
371        if let Ok(mut w) = writer_mutex.lock() {
372            let _ = writeln!(w, "{}", crate::repl::format_event(&event));
373        }
374    };
375
376    // 5. Assemble the autonomous runner and execute until terminal outcome or budget exhaustion.
377    let runner = blyte_agent::run::Runner {
378        provider: provider.as_ref(),
379        shell,
380        fs,
381        context: context_strategy,
382        root,
383        budget: blyte_agent::run::Budget {
384            max_turns: config.max_turns as u32,
385            max_gate_attempts: config.max_gates as u32,
386            max_duration: config.max_seconds.map(std::time::Duration::from_secs),
387        },
388        rollback: config.rollback,
389        on_event: Some(&on_event),
390        research: config.research,
391    };
392
393    let (outcome, report) = runner.run(state);
394    let model_id = provider.model_id();
395
396    let entry = crate::usage_log::Entry {
397        ts: std::time::SystemTime::now()
398            .duration_since(std::time::UNIX_EPOCH)
399            .map(|d| d.as_secs())
400            .unwrap_or(0),
401        repo: crate::usage_log::repo_of(&config.root),
402        session: crate::usage_log::session_from(
403            std::env::var("BLYTE_SESSION").ok(),
404            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
405        ),
406        dispatch: std::env::var("BLYTE_DISPATCH_ID")
407            .ok()
408            .filter(|s| !s.is_empty()),
409        research: config.research,
410        model: model_id.clone(),
411        outcome: format!("{outcome:?}").to_lowercase(),
412        turns: report.outcome_turns,
413        input: report.usage.input,
414        cached: report.usage.cached,
415        output: report.usage.output,
416        thinking: report.usage.thinking,
417        cost_usd: blyte_provider::pricing(&model_id).map(|p| p.cost(&report.usage)),
418    };
419    if let Some(path) = crate::usage_log::default_path() {
420        if let Err(err) = crate::usage_log::append(&path, &entry) {
421            eprintln!("warning: usage log: {err}");
422        }
423    }
424
425    if let Some(path) = &config.report {
426        let mut record = crate::report::RunRecord::from_run(
427            config,
428            &model_id,
429            &outcome,
430            &report,
431            state,
432            started.elapsed(),
433        );
434        record.effort = provider.effort();
435        crate::report::write(path, &record)?;
436    }
437    Ok((outcome, report))
438}