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