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