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`, streaming events to `writer`
260/// and updating the shared `progress` record.
261pub fn run_task_with_state_writer_and_progress<W: Write>(
262    config: &TaskConfig,
263    state: &mut blyte_agent::state::State,
264    writer: &mut W,
265    progress: Arc<Mutex<Progress>>,
266) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
267    check_network_mode(config)?;
268    let started = std::time::Instant::now();
269    if config.orchestrate {
270        if std::env::var("BLYTE_SESSION")
271            .map(|v| v.is_empty())
272            .unwrap_or(true)
273        {
274            let now_secs = std::time::SystemTime::now()
275                .duration_since(std::time::UNIX_EPOCH)
276                .map(|d| d.as_secs())
277                .unwrap_or(0);
278            let id = crate::repl::new_session_id(now_secs, std::process::id());
279            std::env::set_var("BLYTE_SESSION", &id);
280        }
281        if state.orchestrator.instructions.is_none() {
282            let lines = crate::orchestrator_text::set_state_instructions(
283                state,
284                config.dispatch_cmd.is_some(),
285                &config.root,
286            )?;
287            if state.runtime.conversation.is_none() {
288                for line in &lines {
289                    eprintln!("blyte: {line}");
290                }
291            }
292        }
293    }
294    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
295    // 1. Initialize LLM provider from environment credentials or model specification.
296    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
297    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
298        Ok(p) => p,
299        Err(blyte_provider::ProviderError::MissingKey(key)) => {
300            return Err(format!(
301                "Provider error: no API key: set {key} in environment"
302            ));
303        }
304        Err(e) => return Err(format!("Provider error: {e}")),
305    };
306
307    let model_id = provider.model_id();
308    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
309        return Err(format!(
310            "--max-cost needs a known price for {model_id}; none is known"
311        ));
312    }
313    state.orchestrator.max_cost_usd = config.max_cost_usd;
314
315    // 2. Select context assembly strategy.
316    let folded = blyte_agent::context::Folded {
317        // Research quotes code read many turns earlier, so it keeps more before folding.
318        budget_tokens: config.fold_budget.unwrap_or(if config.research {
319            RESEARCH_FOLD_BUDGET
320        } else {
321            blyte_agent::context::Folded::default().budget_tokens
322        }),
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 !config.orchestrate {
350                if let Some(r) = blyte_agent::rules::load(&config.root) {
351                    eprintln!("blyte: repository rules from {}", r.source.display());
352                }
353            }
354            let withheld = blyte_agent::shell::withheld_env();
355            if !withheld.is_empty() {
356                eprintln!(
357                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
358                    withheld.join(", ")
359                );
360            }
361            let shell = if config.sandbox == "on" {
362                if blyte_agent::sandbox::available() {
363                    let profile = blyte_agent::sandbox::default_profile_net(
364                        &config.root,
365                        &config.allow_read,
366                        config.network == "on",
367                    );
368                    if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
369                        eprintln!(
370                            "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
371                        );
372                    }
373                    if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
374                        eprintln!(
375                            "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
376                        );
377                    }
378                    if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } =
379                        &profile
380                    {
381                        eprintln!(
382                            "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
383                        );
384                        if *block_tcp {
385                            eprintln!(
386                                "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
387                            );
388                        }
389                    }
390                    blyte_agent::shell::PersistentShell::local_sandboxed(
391                        config.root.clone(),
392                        profile,
393                    )
394                } else {
395                    eprintln!("warning: sandbox unavailable; running unsandboxed");
396                    blyte_agent::shell::PersistentShell::local(config.root.clone())
397                }
398            } else {
399                blyte_agent::shell::PersistentShell::local(config.root.clone())
400            };
401            (shell, None, config.root.clone())
402        }
403    };
404    let shell: &dyn blyte_agent::shell::Shell = &persistent;
405    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
406        Some(f) => f,
407        None => &local_fs,
408    };
409
410    // 4. Wrap writer in a Mutex so the event callback satisfies Fn trait bounds.
411    let writer_mutex = Mutex::new(writer);
412    let on_event = |event: blyte_agent::run::Event<'_>| {
413        {
414            let mut p = match progress.lock() {
415                Ok(g) => g,
416                Err(e) => e.into_inner(),
417            };
418            match &event {
419                blyte_agent::run::Event::Turn { n, usage, .. } => {
420                    p.turns = *n;
421                    p.usage.input += usage.input;
422                    p.usage.cached += usage.cached;
423                    p.usage.output += usage.output;
424                    p.usage.thinking += usage.thinking;
425                    p.in_gate = false;
426                }
427                blyte_agent::run::Event::GateStart { attempt } => {
428                    p.gate_attempts = *attempt;
429                    p.in_gate = true;
430                }
431                blyte_agent::run::Event::GateSlotWait { ms } => {
432                    p.gate_wait_ms += ms;
433                }
434                blyte_agent::run::Event::Gate { .. } => {
435                    p.in_gate = false;
436                }
437                _ => {}
438            }
439        }
440        if let Ok(mut w) = writer_mutex.lock() {
441            let _ = writeln!(w, "{}", crate::repl::format_event(&event));
442        }
443    };
444
445    // 5. Assemble the autonomous runner and execute until terminal outcome or budget exhaustion.
446    let runner = blyte_agent::run::Runner {
447        provider: provider.as_ref(),
448        shell,
449        fs,
450        context: context_strategy,
451        root,
452        budget: blyte_agent::run::Budget {
453            max_turns: config.max_turns as u32,
454            max_gate_attempts: config.max_gates as u32,
455            max_duration: config.max_seconds.map(std::time::Duration::from_secs),
456        },
457        rollback: config.rollback,
458        on_event: Some(&on_event),
459        research: config.research,
460        claim_check: config.claim_check,
461        base_check: config.base_check,
462    };
463
464    let (outcome, report) = runner.run(state);
465    let model_id = provider.model_id();
466
467    let entry = crate::usage_log::Entry {
468        ts: std::time::SystemTime::now()
469            .duration_since(std::time::UNIX_EPOCH)
470            .map(|d| d.as_secs())
471            .unwrap_or(0),
472        repo: crate::usage_log::repo_of(&config.root),
473        session: crate::usage_log::session_from(
474            std::env::var("BLYTE_SESSION").ok(),
475            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
476        ),
477        dispatch: std::env::var("BLYTE_DISPATCH_ID")
478            .ok()
479            .filter(|s| !s.is_empty()),
480        research: config.research,
481        model: model_id.clone(),
482        outcome: format!("{outcome:?}").to_lowercase(),
483        turns: report.outcome_turns,
484        input: report.usage.input,
485        cached: report.usage.cached,
486        output: report.usage.output,
487        thinking: report.usage.thinking,
488        cost_usd: blyte_provider::pricing(&model_id).map(|p| p.cost(&report.usage)),
489    };
490    if let Some(path) = crate::usage_log::default_path() {
491        if let Err(err) = crate::usage_log::append(&path, &entry) {
492            eprintln!("warning: usage log: {err}");
493        }
494    }
495
496    if let Some(path) = &config.report {
497        let mut record = crate::report::RunRecord::from_run(
498            config,
499            &model_id,
500            &outcome,
501            &report,
502            state,
503            started.elapsed(),
504        );
505        record.effort = provider.effort();
506        crate::report::write(path, &record)?;
507    }
508    Ok((outcome, report))
509}