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