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::{Path, PathBuf};
8use std::sync::{Arc, Condvar, 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    /// Directory containing an untouched checkout of the base commit for background base checks.
70    pub base_check_dir: Option<PathBuf>,
71    /// Whether this run is in converse mode (`--converse`).
72    pub converse: bool,
73    /// Command to run on the host when the conversation model delegates work via the `dispatch` tool (`--dispatch-cmd`).
74    pub dispatch_cmd: Option<String>,
75}
76
77impl From<&crate::cli::Cli> for TaskConfig {
78    /// Maps parsed CLI flags into a concrete `TaskConfig` configuration.
79    fn from(cli: &crate::cli::Cli) -> Self {
80        blyte_agent::tools::set_read_roots(cli.read_roots.clone());
81        // Fall back to current working directory if not running in container mode
82        let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
83
84        let network = match &cli.network {
85            Some(v) => v.clone(),
86            None if cli.converse && cli.sandbox == "on" && cli.container.is_none() => "off".into(),
87            None => "on".into(),
88        };
89
90        Self {
91            prompt: cli.prompt.clone().unwrap_or_default(),
92            gate: cli.gate.clone(),
93            context_strategy: cli.context.clone(),
94            model: cli.model.clone(),
95            container: cli.container.clone(),
96            max_turns: cli.max_turns,
97            max_gates: cli.max_gates,
98            rollback: cli.rollback,
99            root,
100            container_workdir: cli.container_workdir.clone(),
101            max_seconds: cli.max_seconds,
102            max_cost_usd: cli.max_cost_usd,
103            report: cli.report.clone(),
104            fold_budget: cli.fold_budget,
105            sandbox: cli.sandbox.clone(),
106            network,
107            allow_read: cli.allow_read.clone(),
108            pass_env: cli.pass_env.clone(),
109            research: cli.research,
110            claim_check: cli.claim_check,
111            base_check: cli.base_check,
112            base_check_dir: cli.base_check_dir.clone(),
113            converse: cli.converse,
114            dispatch_cmd: cli.dispatch_cmd.clone(),
115        }
116    }
117}
118
119struct TempDirGuard(Option<PathBuf>);
120
121impl Drop for TempDirGuard {
122    fn drop(&mut self) {
123        if let Some(ref path) = self.0 {
124            let _ = std::fs::remove_dir_all(path);
125        }
126    }
127}
128
129pub fn build_sandbox_profile(config: &TaskConfig) -> Result<blyte_agent::sandbox::Profile, String> {
130    Ok(build_sandbox_for_root(config, &config.root)?.0)
131}
132
133fn build_sandbox_for_root(
134    config: &TaskConfig,
135    root: &Path,
136) -> Result<(blyte_agent::sandbox::Profile, Option<PathBuf>), String> {
137    if config.converse {
138        let sandbox = blyte_agent::sandbox::conversation_sandbox_net(
139            root,
140            &config.allow_read,
141            config.network == "on",
142        )?;
143        Ok((sandbox.profile, sandbox.tmpdir))
144    } else {
145        Ok((
146            blyte_agent::sandbox::default_profile_net(
147                root,
148                &config.allow_read,
149                config.network == "on",
150            ),
151            None,
152        ))
153    }
154}
155
156pub struct ConversePolicy {
157    pub allowed_count: usize,
158    pub private_tmpdir: Option<PathBuf>,
159}
160
161pub fn configure_converse_policy_with_paths(
162    converse: bool,
163    sandbox_on: bool,
164    root: &Path,
165    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
166    has_conversation: bool,
167) -> Result<ConversePolicy, String> {
168    if !converse || !sandbox_on {
169        blyte_agent::tools::set_write_scope(None);
170        blyte_agent::tools::set_approval(None);
171        return Ok(ConversePolicy {
172            allowed_count: 0,
173            private_tmpdir: None,
174        });
175    }
176    let is_repo = crate::serve::is_repository(root)?;
177    let paths = blyte_agent::sandbox::conversation_paths(root)?;
178    let mut tmp_cleanup = TempDirGuard(if paths.created_tmpdir {
179        paths.tmpdir.clone()
180    } else {
181        None
182    });
183    let (mut allowed, edit_worktrees) = if is_repo {
184        let tasks_dir = blyte_agent::sandbox::conversation_tasks_dir(root);
185        std::fs::create_dir_all(&tasks_dir)
186            .map_err(|e| format!("cannot create {}: {e}", tasks_dir.display()))?;
187        let tasks_canon = tasks_dir
188            .canonicalize()
189            .map_err(|e| format!("cannot canonicalize {}: {e}", tasks_dir.display()))?;
190        let edit_worktrees = tasks_canon
191            .parent()
192            .map(|p| {
193                p.canonicalize()
194                    .map_err(|e| format!("cannot canonicalize {}: {e}", p.display()))
195            })
196            .transpose()?;
197        (vec![tasks_canon], edit_worktrees)
198    } else {
199        (Vec::new(), None)
200    };
201    for dir in paths.allowed {
202        match dir.canonicalize() {
203            Ok(canon) => {
204                if !allowed.contains(&canon) {
205                    allowed.push(canon);
206                }
207            }
208            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
209            Err(e) => return Err(format!("cannot canonicalize {}: {e}", dir.display())),
210        }
211    }
212    blyte_agent::tools::set_write_scope(Some(blyte_agent::tools::WriteScope {
213        allowed,
214        edit_worktrees,
215    }));
216    let rules = crate::approval_file::load()?;
217    let allowed_count = rules.len();
218    let approver: Arc<dyn blyte_agent::approval::Approver> = match approver {
219        Some(a) => a,
220        None if has_conversation => Arc::new(crate::tty_approver::TtyApprover),
221        None => Arc::new(blyte_agent::approval::NoApprover),
222    };
223    blyte_agent::tools::set_approval(Some(blyte_agent::approval::ApprovalConfig {
224        rules,
225        approver,
226    }));
227    tmp_cleanup.0 = None;
228    Ok(ConversePolicy {
229        allowed_count,
230        private_tmpdir: paths.tmpdir,
231    })
232}
233
234pub fn configure_converse_policy(
235    converse: bool,
236    sandbox_on: bool,
237    root: &Path,
238    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
239    has_conversation: bool,
240) -> Result<usize, String> {
241    Ok(configure_converse_policy_with_paths(
242        converse,
243        sandbox_on,
244        root,
245        approver,
246        has_conversation,
247    )?
248    .allowed_count)
249}
250
251struct BackgroundBaseCheckData {
252    state: blyte_agent::run::BaseCheckState,
253    elapsed_seconds: Option<f64>,
254}
255
256/// Runs the verification gate on the untouched base checkout on a background thread.
257pub struct BackgroundBaseCheck {
258    shared: Arc<(Mutex<BackgroundBaseCheckData>, Condvar)>,
259    cancel: Arc<blyte_agent::shell::CancelHandle>,
260    handle: Mutex<Option<std::thread::JoinHandle<()>>>,
261}
262
263impl BackgroundBaseCheck {
264    /// Starts the gate steps in `base_dir` on a thread using the same shell, sandbox, and
265    /// environment rules as the run's gate.
266    pub fn start(
267        config: &TaskConfig,
268        gate: String,
269        base_dir: PathBuf,
270        deadline: Option<std::time::Instant>,
271    ) -> Result<Self, String> {
272        let cancel = Arc::new(blyte_agent::shell::CancelHandle::new());
273        let shell: Box<dyn blyte_agent::shell::Shell + Send> = match &config.container {
274            Some(cid) => Box::new(blyte_agent::shell::CancellableContainerShell {
275                inner: blyte_agent::shell::ContainerShell {
276                    container_id: cid.clone(),
277                    workdir: base_dir.clone(),
278                },
279                cancel: Arc::clone(&cancel),
280            }),
281            None => {
282                let inner = if config.sandbox == "on" && blyte_agent::sandbox::available() {
283                    let (profile, tmpdir) = build_sandbox_for_root(config, &base_dir)?;
284                    blyte_agent::shell::LocalShell::sandboxed(profile).with_tmpdir(tmpdir)
285                } else {
286                    blyte_agent::shell::LocalShell::new()
287                };
288                Box::new(blyte_agent::shell::CancellableLocalShell {
289                    inner,
290                    cancel: Arc::clone(&cancel),
291                })
292            }
293        };
294        let shared = Arc::new((
295            Mutex::new(BackgroundBaseCheckData {
296                state: blyte_agent::run::BaseCheckState::Pending,
297                elapsed_seconds: None,
298            }),
299            Condvar::new(),
300        ));
301        let thread_shared = Arc::clone(&shared);
302        let thread_cancel = Arc::clone(&cancel);
303        let join = std::thread::spawn(move || {
304            let started = std::time::Instant::now();
305            let mut deadline = deadline;
306            let result = blyte_agent::run::run_gate_steps_cancellable(
307                shell.as_ref(),
308                &gate,
309                &base_dir,
310                &[],
311                &mut deadline,
312                |_| {},
313                &std::time::Instant::now,
314                Some(&thread_cancel),
315            );
316            if thread_cancel.is_cancelled() {
317                return;
318            }
319            let elapsed = started.elapsed().as_secs_f64();
320            let next_state = blyte_agent::run::base_check_state_from_gate(&result);
321            let (lock, cvar) = &*thread_shared;
322            let mut guard = match lock.lock() {
323                Ok(g) => g,
324                Err(e) => e.into_inner(),
325            };
326            guard.state = next_state;
327            guard.elapsed_seconds = Some(elapsed);
328            cvar.notify_all();
329        });
330        Ok(Self {
331            shared,
332            cancel,
333            handle: Mutex::new(Some(join)),
334        })
335    }
336}
337
338impl blyte_agent::run::BaseCheckHandle for BackgroundBaseCheck {
339    fn poll(&self) -> blyte_agent::run::BaseCheckState {
340        let (lock, _) = &*self.shared;
341        match lock.lock() {
342            Ok(g) => g.state.clone(),
343            Err(e) => e.into_inner().state.clone(),
344        }
345    }
346
347    fn wait(&self) -> blyte_agent::run::BaseCheckState {
348        let (lock, cvar) = &*self.shared;
349        let mut guard = match lock.lock() {
350            Ok(g) => g,
351            Err(e) => e.into_inner(),
352        };
353        while matches!(guard.state, blyte_agent::run::BaseCheckState::Pending) {
354            if self.cancel.is_cancelled() {
355                break;
356            }
357            guard = match cvar.wait(guard) {
358                Ok(g) => g,
359                Err(e) => e.into_inner(),
360            };
361        }
362        guard.state.clone()
363    }
364
365    fn stop(&self) {
366        self.cancel.cancel();
367        let (lock, cvar) = &*self.shared;
368        let guard = match lock.lock() {
369            Ok(g) => g,
370            Err(e) => e.into_inner(),
371        };
372        cvar.notify_all();
373        drop(guard);
374        let join = match self.handle.lock() {
375            Ok(mut g) => g.take(),
376            Err(e) => e.into_inner().take(),
377        };
378        if let Some(h) = join {
379            let _ = h.join();
380        }
381    }
382
383    fn elapsed_seconds(&self) -> Option<f64> {
384        let (lock, _) = &*self.shared;
385        match lock.lock() {
386            Ok(g) => g.elapsed_seconds,
387            Err(e) => e.into_inner().elapsed_seconds,
388        }
389    }
390}
391
392impl Drop for BackgroundBaseCheck {
393    fn drop(&mut self) {
394        blyte_agent::run::BaseCheckHandle::stop(self);
395    }
396}
397
398pub fn build_local_shell(
399    config: &TaskConfig,
400) -> Result<blyte_agent::shell::PersistentShell, String> {
401    if config.sandbox == "on" {
402        if blyte_agent::sandbox::available() {
403            let (profile, tmpdir) = build_sandbox_for_root(config, &config.root)?;
404            if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
405                eprintln!(
406                    "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
407                );
408            }
409            if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
410                eprintln!(
411                    "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
412                );
413            }
414            if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } = &profile {
415                eprintln!(
416                    "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
417                );
418                if *block_tcp {
419                    eprintln!(
420                        "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
421                    );
422                }
423            }
424            let shell =
425                blyte_agent::shell::PersistentShell::local_sandboxed(config.root.clone(), profile)
426                    .with_tmpdir(tmpdir);
427            if config.converse {
428                let root = config.root.clone();
429                let allow_read = config.allow_read.clone();
430                let network = config.network == "on";
431                Ok(shell.with_profile_builder(Arc::new(move || {
432                    blyte_agent::sandbox::conversation_profile_for_open_edits(
433                        &root,
434                        &allow_read,
435                        network,
436                    )
437                })))
438            } else {
439                Ok(shell)
440            }
441        } else {
442            eprintln!("warning: sandbox unavailable; running unsandboxed");
443            Ok(blyte_agent::shell::PersistentShell::local(
444                config.root.clone(),
445            ))
446        }
447    } else {
448        Ok(blyte_agent::shell::PersistentShell::local(
449            config.root.clone(),
450        ))
451    }
452}
453
454/// Validates network configuration against the environment and active flags.
455///
456/// Refuses `--network=off` when running with `--container`, when `--sandbox=off`,
457/// when the sandbox is unavailable, or on Linux when `landlock_abi() < 4`.
458pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
459    if config.network == "off" {
460        if config.container.is_some() {
461            return Err(
462                "--network=off is not supported with --container; set the container's network instead"
463                    .into(),
464            );
465        }
466        if config.sandbox != "on" {
467            return Err("--network=off needs the sandbox".into());
468        }
469        #[cfg(target_os = "linux")]
470        if blyte_agent::sandbox::landlock_abi() < 4 {
471            return Err("--network=off on Linux needs Linux 6.7 or later".into());
472        }
473        if !blyte_agent::sandbox::available() {
474            return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
475        }
476    }
477    Ok(())
478}
479
480pub fn write_watchdog_report<F, W: Write>(
481    config: &TaskConfig,
482    progress: &Progress,
483    msg: &str,
484    elapsed: std::time::Duration,
485    resolve_model: F,
486    err_out: &mut W,
487) -> Result<Option<crate::report::RunRecord>, String>
488where
489    F: FnOnce(Option<&str>) -> Result<String, String>,
490{
491    let Some(path) = &config.report else {
492        return Ok(None);
493    };
494    let mut record = crate::report::RunRecord::from_error(config, msg, elapsed);
495    record.turns = progress.turns;
496    record.gate_attempts = progress.gate_attempts;
497    record.usage = crate::report::UsageRecord {
498        input: progress.usage.input,
499        cached: progress.usage.cached,
500        output: progress.usage.output,
501        thinking: progress.usage.thinking,
502    };
503    let model_id = match resolve_model(config.model.as_deref()) {
504        Ok(id) if !id.is_empty() => Some(id),
505        Ok(_) => {
506            let _ = writeln!(
507                err_out,
508                "blyte: watchdog warning: provider returned empty model id"
509            );
510            config.model.clone().filter(|m| !m.is_empty())
511        }
512        Err(err) => {
513            let _ = writeln!(
514                err_out,
515                "blyte: watchdog warning: could not resolve provider for cost lookup: {err}"
516            );
517            config.model.clone().filter(|m| !m.is_empty())
518        }
519    };
520    if let Some(id) = model_id {
521        record.cost_usd = blyte_provider::pricing(&id).map(|pr| pr.cost(&progress.usage));
522        record.model_id = Some(id);
523    }
524    crate::report::write(path, &record)?;
525    Ok(Some(record))
526}
527
528/// Executes an autonomous solver run using the provided task configuration and live stdout.
529///
530/// Configures the AI provider, context strategy, execution environment (local or container),
531/// and deterministic gate loop, printing live event progress as turns execute.
532///
533/// # Arguments
534///
535/// * `config` - Parameters governing prompt, budgets, gate verification, and environment.
536///
537/// # Returns
538///
539/// Returns `Ok((Outcome, RunReport))` containing final completion status and metrics,
540/// or an `Err(String)` describing initialization failure.
541pub fn run_task(
542    config: TaskConfig,
543) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
544    let started = std::time::Instant::now();
545    let progress = Arc::new(Mutex::new(Progress::default()));
546    if let Some(s) = config.max_seconds {
547        // BLYTE_WATCHDOG_GRACE_SECS exists for tests.
548        let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
549            .ok()
550            .and_then(|v| v.trim().parse().ok())
551            .unwrap_or(30);
552        let watchdog_config = config.clone();
553        let watchdog_progress = Arc::clone(&progress);
554        std::thread::spawn(move || {
555            loop {
556                let wait_ms = match watchdog_progress.lock() {
557                    Ok(g) => g.gate_wait_ms,
558                    Err(e) => e.into_inner().gate_wait_ms,
559                };
560                let deadline = started
561                    + std::time::Duration::from_secs(s.saturating_add(grace_secs))
562                    + std::time::Duration::from_millis(wait_ms);
563                match deadline.checked_duration_since(std::time::Instant::now()) {
564                    Some(remaining) if !remaining.is_zero() => {
565                        std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
566                    }
567                    _ => break,
568                }
569            }
570            let p = match watchdog_progress.lock() {
571                Ok(g) => *g,
572                Err(e) => *e.into_inner(),
573            };
574            let msg = if p.in_gate {
575                format!(
576                    "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
577                    p.gate_attempts
578                )
579            } else {
580                format!(
581                    "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
582                    p.turns
583                )
584            };
585            let mut stderr = std::io::stderr();
586            if let Err(err) = write_watchdog_report(
587                &watchdog_config,
588                &p,
589                &msg,
590                started.elapsed(),
591                |m| {
592                    blyte_provider::resolve_provider(m)
593                        .map(|pr| pr.model_id())
594                        .map_err(|e| e.to_string())
595                },
596                &mut stderr,
597            ) {
598                eprintln!("blyte: watchdog failed to write report: {err}");
599            }
600            eprintln!("blyte: {msg}");
601            std::process::exit(1);
602        });
603    }
604    let verification_cmd = config.gate.as_deref().unwrap_or("");
605    let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
606    state.brief.max_cost_usd = config.max_cost_usd;
607    let mut stdout = std::io::stdout();
608    let result =
609        run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
610    // The loop writes its own report; this covers a run that never reached it (e.g. no API
611    // key), so a caller always finds one. An absent report would read as a crash.
612    if let (Err(e), Some(path)) = (&result, &config.report) {
613        crate::report::write(
614            path,
615            &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
616        )?;
617    }
618    result
619}
620
621/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`.
622///
623/// Preserves session mutations (epistemic ledger, patches, attempts) directly in the provided `state`.
624///
625/// # Arguments
626///
627/// * `config` - Execution parameters.
628/// * `state` - The mutable session state to advance.
629/// * `writer` - Stream writer sink for formatted events.
630///
631/// # Returns
632///
633/// Returns `Ok((Outcome, RunReport))` or an `Err(String)` describing failure.
634pub fn run_task_with_state_and_writer<W: Write>(
635    config: &TaskConfig,
636    state: &mut blyte_agent::state::State,
637    writer: &mut W,
638) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
639    let progress = Arc::new(Mutex::new(Progress::default()));
640    run_task_with_state_writer_and_progress(config, state, writer, progress)
641}
642
643/// Executes an autonomous solver run against an existing mutable `State`, passing every raw event
644/// directly to `on_event` without formatting lines to a writer.
645pub fn run_task_with_state_and_events(
646    config: &TaskConfig,
647    state: &mut blyte_agent::state::State,
648    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
649) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
650    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
651    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
652}
653
654pub fn run_task_with_state_and_max_duration(
655    config: &TaskConfig,
656    state: &mut blyte_agent::state::State,
657    max_duration: Option<std::time::Duration>,
658    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
659) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
660    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
661}
662
663/// Executes an autonomous solver run with an explicit approver override (used by the surface).
664pub fn run_task_with_approver(
665    config: &TaskConfig,
666    state: &mut blyte_agent::state::State,
667    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
668    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
669) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
670    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
671    run_task_with_event_callback(config, state, approver, max_duration, &|event| {
672        on_event(event)
673    })
674}
675
676/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
677/// and updating the shared `progress` record.
678pub fn run_task_with_state_writer_and_progress<W: Write>(
679    config: &TaskConfig,
680    state: &mut blyte_agent::state::State,
681    writer: &mut W,
682    progress: Arc<Mutex<Progress>>,
683) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
684    let writer_mutex = Mutex::new(writer);
685    let on_event = |event: &blyte_agent::run::Event<'_>| {
686        {
687            let mut p = match progress.lock() {
688                Ok(g) => g,
689                Err(e) => e.into_inner(),
690            };
691            match event {
692                blyte_agent::run::Event::Turn { n, usage, .. } => {
693                    p.turns = *n;
694                    p.usage.input += usage.input;
695                    p.usage.cached += usage.cached;
696                    p.usage.output += usage.output;
697                    p.usage.thinking += usage.thinking;
698                    p.in_gate = false;
699                }
700                blyte_agent::run::Event::GateStart { attempt } => {
701                    p.gate_attempts = *attempt;
702                    p.in_gate = true;
703                }
704                blyte_agent::run::Event::GateSlotWait { ms } => {
705                    p.gate_wait_ms += ms;
706                }
707                blyte_agent::run::Event::Gate { .. } => {
708                    p.in_gate = false;
709                }
710                _ => {}
711            }
712        }
713        let line = crate::repl::format_event(event);
714        if !line.is_empty() {
715            if let Ok(mut w) = writer_mutex.lock() {
716                let _ = writeln!(w, "{line}");
717            }
718        }
719    };
720    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
721    run_task_with_event_callback(config, state, None, max_duration, &on_event)
722}
723
724fn build_usage_entry(
725    config: &TaskConfig,
726    model_id: &str,
727    outcome: String,
728    turns: u32,
729    usage: &blyte_provider::Usage,
730) -> crate::usage_log::Entry {
731    crate::usage_log::Entry {
732        ts: std::time::SystemTime::now()
733            .duration_since(std::time::UNIX_EPOCH)
734            .map(|d| d.as_secs())
735            .unwrap_or(0),
736        repo: crate::usage_log::repo_of(&config.root),
737        session: crate::usage_log::session_from(
738            std::env::var("BLYTE_SESSION").ok(),
739            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
740        ),
741        dispatch: std::env::var("BLYTE_DISPATCH_ID")
742            .ok()
743            .filter(|s| !s.is_empty()),
744        research: config.research,
745        model: model_id.to_string(),
746        outcome,
747        turns,
748        input: usage.input,
749        cached: usage.cached,
750        output: usage.output,
751        thinking: usage.thinking,
752        cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
753    }
754}
755
756#[derive(Debug, PartialEq, Eq)]
757struct ExceededField {
758    field: &'static str,
759    written: u64,
760    total: u64,
761}
762
763fn usage_remainder(
764    total_turns: u32,
765    total_usage: &blyte_provider::Usage,
766    written_turns: u32,
767    written_usage: &blyte_provider::Usage,
768) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
769    let mut exceeded = Vec::new();
770    if written_turns > total_turns {
771        exceeded.push(ExceededField {
772            field: "turns",
773            written: u64::from(written_turns),
774            total: u64::from(total_turns),
775        });
776    }
777    if written_usage.input > total_usage.input {
778        exceeded.push(ExceededField {
779            field: "input",
780            written: written_usage.input,
781            total: total_usage.input,
782        });
783    }
784    if written_usage.cached > total_usage.cached {
785        exceeded.push(ExceededField {
786            field: "cached",
787            written: written_usage.cached,
788            total: total_usage.cached,
789        });
790    }
791    if written_usage.output > total_usage.output {
792        exceeded.push(ExceededField {
793            field: "output",
794            written: written_usage.output,
795            total: total_usage.output,
796        });
797    }
798    if written_usage.thinking > total_usage.thinking {
799        exceeded.push(ExceededField {
800            field: "thinking",
801            written: written_usage.thinking,
802            total: total_usage.thinking,
803        });
804    }
805    if !exceeded.is_empty() {
806        return Err(exceeded);
807    }
808    Ok((
809        total_turns - written_turns,
810        blyte_provider::Usage {
811            input: total_usage.input - written_usage.input,
812            cached: total_usage.cached - written_usage.cached,
813            output: total_usage.output - written_usage.output,
814            thinking: total_usage.thinking - written_usage.thinking,
815        },
816    ))
817}
818
819fn run_task_with_event_callback(
820    config: &TaskConfig,
821    state: &mut blyte_agent::state::State,
822    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
823    max_duration: Option<std::time::Duration>,
824    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
825) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
826    check_network_mode(config)?;
827    let started = std::time::Instant::now();
828    let _one_shot_tmp_guard = if config.converse {
829        if std::env::var("BLYTE_SESSION")
830            .map(|v| v.is_empty())
831            .unwrap_or(true)
832        {
833            let now_secs = std::time::SystemTime::now()
834                .duration_since(std::time::UNIX_EPOCH)
835                .map(|d| d.as_secs())
836                .unwrap_or(0);
837            let id = crate::repl::new_session_id(now_secs, std::process::id());
838            std::env::set_var("BLYTE_SESSION", &id);
839        }
840        let sandbox_on = config.sandbox == "on";
841        let policy = configure_converse_policy_with_paths(
842            true,
843            sandbox_on,
844            &config.root,
845            approver,
846            state.runtime.conversation.is_some(),
847        )?;
848        let guard = if state.runtime.conversation.is_none() {
849            policy.private_tmpdir.map(|p| TempDirGuard(Some(p)))
850        } else {
851            None
852        };
853        if state.brief.instructions.is_none() {
854            let lines = crate::conversation_text::set_state_instructions(
855                state,
856                config.dispatch_cmd.is_some(),
857                &config.root,
858                sandbox_on,
859                policy.allowed_count,
860            )?;
861            if state.runtime.conversation.is_none() {
862                for line in &lines {
863                    eprintln!("blyte: {line}");
864                }
865            }
866        }
867        let exe = std::env::current_exe()
868            .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
869        blyte_agent::tools::set_blyte_tool(Some(exe));
870        guard
871    } else {
872        configure_converse_policy(false, false, &config.root, None, false)?;
873        blyte_agent::tools::set_blyte_tool(None);
874        None
875    };
876    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
877    // 1. Initialize LLM provider from environment credentials or model specification.
878    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
879    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
880        Ok(p) => p,
881        Err(blyte_provider::ProviderError::MissingKey(key)) => {
882            return Err(format!(
883                "Provider error: no API key: set {key} in environment"
884            ));
885        }
886        Err(e) => return Err(format!("Provider error: {e}")),
887    };
888
889    let model_id = provider.model_id();
890    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
891        return Err(format!(
892            "--max-cost needs a known price for {model_id}; none is known"
893        ));
894    }
895    state.brief.max_cost_usd = config.max_cost_usd;
896
897    // 2. Select context assembly strategy.
898    let folded = blyte_agent::context::Folded {
899        // Research quotes code read many turns earlier, so it keeps more before folding.
900        budget_tokens: config.fold_budget.unwrap_or(if config.research {
901            RESEARCH_FOLD_BUDGET
902        } else {
903            blyte_agent::context::Folded::default().budget_tokens
904        }),
905    };
906    let conversational = blyte_agent::context::Conversational;
907    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
908        match config.context_strategy.as_str() {
909            "conversational" => &conversational,
910            _ => &folded,
911        };
912
913    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
914    // and `export` carry over). Container files go through a session too. Each falls back to a
915    // process per command if a session cannot start.
916    let local_fs = blyte_agent::fs::LocalFs;
917    let (persistent, session_fs, root) = match &config.container {
918        Some(cid) => (
919            blyte_agent::shell::PersistentShell::container(
920                cid.clone(),
921                PathBuf::from(&config.container_workdir),
922            ),
923            Some(blyte_agent::fs::SessionFs::container(
924                cid.clone(),
925                PathBuf::from(&config.container_workdir),
926            )),
927            PathBuf::from(&config.container_workdir),
928        ),
929        None => {
930            blyte_agent::shell::set_pass_env(config.pass_env.clone());
931            if !config.converse {
932                if let Some(r) = blyte_agent::rules::load(&config.root) {
933                    eprintln!("blyte: repository rules from {}", r.source.display());
934                }
935            }
936            let withheld = blyte_agent::shell::withheld_env();
937            if !withheld.is_empty() {
938                eprintln!(
939                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
940                    withheld.join(", ")
941                );
942            }
943            let shell = build_local_shell(config)?;
944            (shell, None, config.root.clone())
945        }
946    };
947    let shell: &dyn blyte_agent::shell::Shell = &persistent;
948    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
949        Some(f) => f,
950        None => &local_fs,
951    };
952
953    let usage_path = crate::usage_log::default_path();
954    let written = Mutex::new((0u32, blyte_provider::Usage::default()));
955    let runner_on_event = |event: blyte_agent::run::Event<'_>| {
956        if let blyte_agent::run::Event::Turn { usage, .. } = &event {
957            if let Some(path) = &usage_path {
958                let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
959                match crate::usage_log::append(path, &entry) {
960                    Ok(()) => {
961                        let mut w = match written.lock() {
962                            Ok(g) => g,
963                            Err(e) => e.into_inner(),
964                        };
965                        w.0 += 1;
966                        w.1.input += usage.input;
967                        w.1.cached += usage.cached;
968                        w.1.output += usage.output;
969                        w.1.thinking += usage.thinking;
970                    }
971                    Err(err) => eprintln!("warning: usage log: {err}"),
972                }
973            }
974        }
975        on_event(&event);
976    };
977
978    let bg_base_check = match &config.base_check_dir {
979        Some(base_dir)
980            if !blyte_agent::run::gate_steps(&state.brief.verification_cmd).is_empty() =>
981        {
982            let deadline = max_duration.map(|d| std::time::Instant::now() + d);
983            Some(BackgroundBaseCheck::start(
984                config,
985                state.brief.verification_cmd.clone(),
986                base_dir.clone(),
987                deadline,
988            )?)
989        }
990        _ => None,
991    };
992    let base_check = if let Some(ref bg) = bg_base_check {
993        blyte_agent::run::BaseCheck::Polled(bg)
994    } else if config.base_check {
995        blyte_agent::run::BaseCheck::BeforeFirstTurn
996    } else {
997        blyte_agent::run::BaseCheck::None
998    };
999
1000    let runner = blyte_agent::run::Runner {
1001        provider: provider.as_ref(),
1002        shell,
1003        fs,
1004        context: context_strategy,
1005        root,
1006        budget: blyte_agent::run::Budget {
1007            max_turns: config.max_turns as u32,
1008            max_gate_attempts: config.max_gates as u32,
1009            max_duration,
1010        },
1011        rollback: config.rollback,
1012        on_event: Some(&runner_on_event),
1013        research: config.research,
1014        claim_check: config.claim_check,
1015        base_check,
1016    };
1017
1018    let (outcome, report) = runner.run(state);
1019    drop(bg_base_check);
1020
1021    if let Some(path) = &usage_path {
1022        let (written_turns, written_usage) = match written.lock() {
1023            Ok(g) => *g,
1024            Err(e) => *e.into_inner(),
1025        };
1026        let (closing_turns, closing_usage) = match usage_remainder(
1027            report.outcome_turns,
1028            &report.usage,
1029            written_turns,
1030            &written_usage,
1031        ) {
1032            Ok(rem) => rem,
1033            Err(exceeded) => {
1034                for ExceededField {
1035                    field,
1036                    written,
1037                    total,
1038                } in exceeded
1039                {
1040                    eprintln!(
1041                        "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
1042                    );
1043                }
1044                (0, blyte_provider::Usage::default())
1045            }
1046        };
1047        let entry = build_usage_entry(
1048            config,
1049            &model_id,
1050            format!("{outcome:?}").to_lowercase(),
1051            closing_turns,
1052            &closing_usage,
1053        );
1054        if let Err(err) = crate::usage_log::append(path, &entry) {
1055            eprintln!("warning: usage log: {err}");
1056        }
1057    }
1058
1059    if let Some(path) = &config.report {
1060        let mut record = crate::report::RunRecord::from_run(
1061            config,
1062            &model_id,
1063            &outcome,
1064            &report,
1065            state,
1066            started.elapsed(),
1067        );
1068        record.effort = provider.effort();
1069        crate::report::write(path, &record)?;
1070    }
1071    Ok((outcome, report))
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077
1078    #[test]
1079    fn usage_remainder_computes_exact_and_partial_remainders() {
1080        let total = blyte_provider::Usage {
1081            input: 600,
1082            cached: 150,
1083            output: 90,
1084            thinking: 75,
1085        };
1086        let exact = usage_remainder(3, &total, 3, &total).unwrap();
1087        assert_eq!(exact, (0, blyte_provider::Usage::default()));
1088
1089        let written = blyte_provider::Usage {
1090            input: 500,
1091            cached: 100,
1092            output: 80,
1093            thinking: 50,
1094        };
1095        let partial = usage_remainder(3, &total, 2, &written).unwrap();
1096        assert_eq!(
1097            partial,
1098            (
1099                1,
1100                blyte_provider::Usage {
1101                    input: 100,
1102                    cached: 50,
1103                    output: 10,
1104                    thinking: 25,
1105                }
1106            )
1107        );
1108    }
1109
1110    #[test]
1111    fn usage_remainder_reports_exceeding_fields() {
1112        let total = blyte_provider::Usage {
1113            input: 100,
1114            cached: 20,
1115            output: 30,
1116            thinking: 10,
1117        };
1118        let written = blyte_provider::Usage {
1119            input: 120,
1120            cached: 20,
1121            output: 35,
1122            thinking: 10,
1123        };
1124        let err = usage_remainder(2, &total, 3, &written).unwrap_err();
1125        assert_eq!(
1126            err,
1127            vec![
1128                ExceededField {
1129                    field: "turns",
1130                    written: 3,
1131                    total: 2,
1132                },
1133                ExceededField {
1134                    field: "input",
1135                    written: 120,
1136                    total: 100,
1137                },
1138                ExceededField {
1139                    field: "output",
1140                    written: 35,
1141                    total: 30,
1142                },
1143            ]
1144        );
1145    }
1146
1147    fn test_task_config(root: &Path, report: Option<PathBuf>, model: Option<String>) -> TaskConfig {
1148        TaskConfig {
1149            prompt: "test".to_string(),
1150            gate: Some("true".to_string()),
1151            context_strategy: "folded".to_string(),
1152            model,
1153            container: None,
1154            max_turns: 10,
1155            max_gates: 3,
1156            rollback: false,
1157            root: root.to_path_buf(),
1158            container_workdir: "/workspace".to_string(),
1159            max_seconds: Some(10),
1160            max_cost_usd: None,
1161            report,
1162            fold_budget: None,
1163            sandbox: "off".to_string(),
1164            network: "on".to_string(),
1165            allow_read: Vec::new(),
1166            pass_env: Vec::new(),
1167            research: false,
1168            claim_check: false,
1169            base_check: false,
1170            base_check_dir: None,
1171            converse: false,
1172            dispatch_cmd: None,
1173        }
1174    }
1175
1176    #[test]
1177    fn watchdog_report_write_failure_names_path_and_model_id_is_never_empty() {
1178        let dir = tempfile::tempdir().unwrap();
1179        let report_dir = dir.path().join("unwritable.report.json");
1180        std::fs::create_dir_all(&report_dir).unwrap();
1181
1182        let cfg = test_task_config(dir.path(), Some(report_dir.clone()), None);
1183        let progress = Progress {
1184            turns: 2,
1185            gate_attempts: 1,
1186            in_gate: false,
1187            gate_wait_ms: 0,
1188            usage: blyte_provider::Usage {
1189                input: 1000,
1190                cached: 0,
1191                output: 500,
1192                thinking: 0,
1193            },
1194        };
1195        let mut err_buf = Vec::new();
1196        let err = write_watchdog_report(
1197            &cfg,
1198            &progress,
1199            "stopped past --max-seconds",
1200            std::time::Duration::from_secs(5),
1201            |_| Err("missing API key".to_string()),
1202            &mut err_buf,
1203        )
1204        .expect_err("writing watchdog report to a directory must fail");
1205
1206        assert!(
1207            err.contains(&report_dir.display().to_string()),
1208            "write error must name report path, got: {err}"
1209        );
1210        let warning = String::from_utf8(err_buf).unwrap();
1211        assert!(
1212            warning.contains("missing API key"),
1213            "provider resolution error must be logged, got: {warning}"
1214        );
1215
1216        let ok_report = dir.path().join("ok.report.json");
1217        let ok_cfg = test_task_config(dir.path(), Some(ok_report.clone()), None);
1218        let mut ok_err = Vec::new();
1219        let rec = write_watchdog_report(
1220            &ok_cfg,
1221            &progress,
1222            "stopped past --max-seconds",
1223            std::time::Duration::from_secs(5),
1224            |_| Ok("gemini-3.8-flash-high".to_string()),
1225            &mut ok_err,
1226        )
1227        .expect("writing watchdog report to file must succeed")
1228        .expect("record must be returned");
1229
1230        assert_eq!(rec.model_id.as_deref(), Some("gemini-3.8-flash-high"));
1231        assert!(rec.cost_usd.is_some());
1232
1233        let fallback_report = dir.path().join("fallback.report.json");
1234        let fallback_cfg = test_task_config(dir.path(), Some(fallback_report), None);
1235        let mut fallback_err = Vec::new();
1236        let fallback_rec = write_watchdog_report(
1237            &fallback_cfg,
1238            &progress,
1239            "stopped past --max-seconds",
1240            std::time::Duration::from_secs(5),
1241            |_| Err("no provider".to_string()),
1242            &mut fallback_err,
1243        )
1244        .expect("writing watchdog report must succeed")
1245        .expect("record must be returned");
1246
1247        assert_ne!(fallback_rec.model_id.as_deref(), Some(""));
1248        assert_eq!(fallback_rec.model_id, None);
1249        assert!(String::from_utf8(fallback_err)
1250            .unwrap()
1251            .contains("no provider"));
1252    }
1253}