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