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