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    let mut stdout = std::io::stdout();
224    let result =
225        run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
226    // The loop writes its own report; this covers a run that never reached it (e.g. no API
227    // key), so a caller always finds one. An absent report would read as a crash.
228    if let (Err(e), Some(path)) = (&result, &config.report) {
229        crate::report::write(
230            path,
231            &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
232        )?;
233    }
234    result
235}
236
237/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`.
238///
239/// Preserves session mutations (epistemic ledger, patches, attempts) directly in the provided `state`.
240///
241/// # Arguments
242///
243/// * `config` - Execution parameters.
244/// * `state` - The mutable session state to advance.
245/// * `writer` - Stream writer sink for formatted events.
246///
247/// # Returns
248///
249/// Returns `Ok((Outcome, RunReport))` or an `Err(String)` describing failure.
250pub fn run_task_with_state_and_writer<W: Write>(
251    config: &TaskConfig,
252    state: &mut blyte_agent::state::State,
253    writer: &mut W,
254) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
255    let progress = Arc::new(Mutex::new(Progress::default()));
256    run_task_with_state_writer_and_progress(config, state, writer, progress)
257}
258
259/// Executes an autonomous solver run against an existing mutable `State`, passing every raw event
260/// directly to `on_event` without formatting lines to a writer.
261pub fn run_task_with_state_and_events(
262    config: &TaskConfig,
263    state: &mut blyte_agent::state::State,
264    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
265) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
266    run_task_with_event_callback(config, state, &|event| on_event(event))
267}
268
269/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
270/// and updating the shared `progress` record.
271pub fn run_task_with_state_writer_and_progress<W: Write>(
272    config: &TaskConfig,
273    state: &mut blyte_agent::state::State,
274    writer: &mut W,
275    progress: Arc<Mutex<Progress>>,
276) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
277    let writer_mutex = Mutex::new(writer);
278    let on_event = |event: &blyte_agent::run::Event<'_>| {
279        {
280            let mut p = match progress.lock() {
281                Ok(g) => g,
282                Err(e) => e.into_inner(),
283            };
284            match event {
285                blyte_agent::run::Event::Turn { n, usage, .. } => {
286                    p.turns = *n;
287                    p.usage.input += usage.input;
288                    p.usage.cached += usage.cached;
289                    p.usage.output += usage.output;
290                    p.usage.thinking += usage.thinking;
291                    p.in_gate = false;
292                }
293                blyte_agent::run::Event::GateStart { attempt } => {
294                    p.gate_attempts = *attempt;
295                    p.in_gate = true;
296                }
297                blyte_agent::run::Event::GateSlotWait { ms } => {
298                    p.gate_wait_ms += ms;
299                }
300                blyte_agent::run::Event::Gate { .. } => {
301                    p.in_gate = false;
302                }
303                _ => {}
304            }
305        }
306        let line = crate::repl::format_event(event);
307        if !line.is_empty() {
308            if let Ok(mut w) = writer_mutex.lock() {
309                let _ = writeln!(w, "{line}");
310            }
311        }
312    };
313    run_task_with_event_callback(config, state, &on_event)
314}
315
316fn run_task_with_event_callback(
317    config: &TaskConfig,
318    state: &mut blyte_agent::state::State,
319    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
320) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
321    check_network_mode(config)?;
322    let started = std::time::Instant::now();
323    if config.orchestrate {
324        if std::env::var("BLYTE_SESSION")
325            .map(|v| v.is_empty())
326            .unwrap_or(true)
327        {
328            let now_secs = std::time::SystemTime::now()
329                .duration_since(std::time::UNIX_EPOCH)
330                .map(|d| d.as_secs())
331                .unwrap_or(0);
332            let id = crate::repl::new_session_id(now_secs, std::process::id());
333            std::env::set_var("BLYTE_SESSION", &id);
334        }
335        if state.orchestrator.instructions.is_none() {
336            let lines = crate::orchestrator_text::set_state_instructions(
337                state,
338                config.dispatch_cmd.is_some(),
339                &config.root,
340            )?;
341            if state.runtime.conversation.is_none() {
342                for line in &lines {
343                    eprintln!("blyte: {line}");
344                }
345            }
346        }
347    }
348    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
349    // 1. Initialize LLM provider from environment credentials or model specification.
350    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
351    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
352        Ok(p) => p,
353        Err(blyte_provider::ProviderError::MissingKey(key)) => {
354            return Err(format!(
355                "Provider error: no API key: set {key} in environment"
356            ));
357        }
358        Err(e) => return Err(format!("Provider error: {e}")),
359    };
360
361    let model_id = provider.model_id();
362    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
363        return Err(format!(
364            "--max-cost needs a known price for {model_id}; none is known"
365        ));
366    }
367    state.orchestrator.max_cost_usd = config.max_cost_usd;
368
369    // 2. Select context assembly strategy.
370    let folded = blyte_agent::context::Folded {
371        // Research quotes code read many turns earlier, so it keeps more before folding.
372        budget_tokens: config.fold_budget.unwrap_or(if config.research {
373            RESEARCH_FOLD_BUDGET
374        } else {
375            blyte_agent::context::Folded::default().budget_tokens
376        }),
377    };
378    let conversational = blyte_agent::context::Conversational;
379    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
380        match config.context_strategy.as_str() {
381            "conversational" => &conversational,
382            _ => &folded,
383        };
384
385    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
386    // and `export` carry over). Container files go through a session too. Each falls back to a
387    // process per command if a session cannot start.
388    let local_fs = blyte_agent::fs::LocalFs;
389    let (persistent, session_fs, root) = match &config.container {
390        Some(cid) => (
391            blyte_agent::shell::PersistentShell::container(
392                cid.clone(),
393                PathBuf::from(&config.container_workdir),
394            ),
395            Some(blyte_agent::fs::SessionFs::container(
396                cid.clone(),
397                PathBuf::from(&config.container_workdir),
398            )),
399            PathBuf::from(&config.container_workdir),
400        ),
401        None => {
402            blyte_agent::shell::set_pass_env(config.pass_env.clone());
403            if !config.orchestrate {
404                if let Some(r) = blyte_agent::rules::load(&config.root) {
405                    eprintln!("blyte: repository rules from {}", r.source.display());
406                }
407            }
408            let withheld = blyte_agent::shell::withheld_env();
409            if !withheld.is_empty() {
410                eprintln!(
411                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
412                    withheld.join(", ")
413                );
414            }
415            let shell = if config.sandbox == "on" {
416                if blyte_agent::sandbox::available() {
417                    let profile = blyte_agent::sandbox::default_profile_net(
418                        &config.root,
419                        &config.allow_read,
420                        config.network == "on",
421                    );
422                    if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
423                        eprintln!(
424                            "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
425                        );
426                    }
427                    if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
428                        eprintln!(
429                            "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
430                        );
431                    }
432                    if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } =
433                        &profile
434                    {
435                        eprintln!(
436                            "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
437                        );
438                        if *block_tcp {
439                            eprintln!(
440                                "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
441                            );
442                        }
443                    }
444                    blyte_agent::shell::PersistentShell::local_sandboxed(
445                        config.root.clone(),
446                        profile,
447                    )
448                } else {
449                    eprintln!("warning: sandbox unavailable; running unsandboxed");
450                    blyte_agent::shell::PersistentShell::local(config.root.clone())
451                }
452            } else {
453                blyte_agent::shell::PersistentShell::local(config.root.clone())
454            };
455            (shell, None, config.root.clone())
456        }
457    };
458    let shell: &dyn blyte_agent::shell::Shell = &persistent;
459    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
460        Some(f) => f,
461        None => &local_fs,
462    };
463
464    let runner_on_event = |event: blyte_agent::run::Event<'_>| on_event(&event);
465
466    let runner = blyte_agent::run::Runner {
467        provider: provider.as_ref(),
468        shell,
469        fs,
470        context: context_strategy,
471        root,
472        budget: blyte_agent::run::Budget {
473            max_turns: config.max_turns as u32,
474            max_gate_attempts: config.max_gates as u32,
475            max_duration: config.max_seconds.map(std::time::Duration::from_secs),
476        },
477        rollback: config.rollback,
478        on_event: Some(&runner_on_event),
479        research: config.research,
480        claim_check: config.claim_check,
481        base_check: config.base_check,
482    };
483
484    let (outcome, report) = runner.run(state);
485    let model_id = provider.model_id();
486
487    let entry = crate::usage_log::Entry {
488        ts: std::time::SystemTime::now()
489            .duration_since(std::time::UNIX_EPOCH)
490            .map(|d| d.as_secs())
491            .unwrap_or(0),
492        repo: crate::usage_log::repo_of(&config.root),
493        session: crate::usage_log::session_from(
494            std::env::var("BLYTE_SESSION").ok(),
495            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
496        ),
497        dispatch: std::env::var("BLYTE_DISPATCH_ID")
498            .ok()
499            .filter(|s| !s.is_empty()),
500        research: config.research,
501        model: model_id.clone(),
502        outcome: format!("{outcome:?}").to_lowercase(),
503        turns: report.outcome_turns,
504        input: report.usage.input,
505        cached: report.usage.cached,
506        output: report.usage.output,
507        thinking: report.usage.thinking,
508        cost_usd: blyte_provider::pricing(&model_id).map(|p| p.cost(&report.usage)),
509    };
510    if let Some(path) = crate::usage_log::default_path() {
511        if let Err(err) = crate::usage_log::append(&path, &entry) {
512            eprintln!("warning: usage log: {err}");
513        }
514    }
515
516    if let Some(path) = &config.report {
517        let mut record = crate::report::RunRecord::from_run(
518            config,
519            &model_id,
520            &outcome,
521            &report,
522            state,
523            started.elapsed(),
524        );
525        record.effort = provider.effort();
526        crate::report::write(path, &record)?;
527    }
528    Ok((outcome, report))
529}