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
819/// Whether to print the list of withheld environment variables: once for each distinct list in
820/// this process. A surface runs many turns in one process, and the list is the same for each.
821fn withheld_notice_is_due(withheld: &[String]) -> bool {
822    static SHOWN: std::sync::Mutex<Option<Vec<String>>> = std::sync::Mutex::new(None);
823    if withheld.is_empty() {
824        return false;
825    }
826    let mut shown = SHOWN.lock().unwrap_or_else(|e| e.into_inner());
827    if shown.as_deref() == Some(withheld) {
828        return false;
829    }
830    *shown = Some(withheld.to_vec());
831    true
832}
833
834fn run_task_with_event_callback(
835    config: &TaskConfig,
836    state: &mut blyte_agent::state::State,
837    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
838    max_duration: Option<std::time::Duration>,
839    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
840) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
841    check_network_mode(config)?;
842    let started = std::time::Instant::now();
843    let _one_shot_tmp_guard = if config.converse {
844        if std::env::var("BLYTE_SESSION")
845            .map(|v| v.is_empty())
846            .unwrap_or(true)
847        {
848            let now_secs = std::time::SystemTime::now()
849                .duration_since(std::time::UNIX_EPOCH)
850                .map(|d| d.as_secs())
851                .unwrap_or(0);
852            let id = crate::repl::new_session_id(now_secs, std::process::id());
853            std::env::set_var("BLYTE_SESSION", &id);
854        }
855        let sandbox_on = config.sandbox == "on";
856        let policy = configure_converse_policy_with_paths(
857            true,
858            sandbox_on,
859            &config.root,
860            approver,
861            state.runtime.conversation.is_some(),
862        )?;
863        let guard = if state.runtime.conversation.is_none() {
864            policy.private_tmpdir.map(|p| TempDirGuard(Some(p)))
865        } else {
866            None
867        };
868        if state.brief.instructions.is_none() {
869            let lines = crate::conversation_text::set_state_instructions(
870                state,
871                config.dispatch_cmd.is_some(),
872                &config.root,
873                sandbox_on,
874                policy.allowed_count,
875            )?;
876            if state.runtime.conversation.is_none() {
877                for line in &lines {
878                    eprintln!("blyte: {line}");
879                }
880            }
881        }
882        let exe = std::env::current_exe()
883            .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
884        blyte_agent::tools::set_blyte_tool(Some(exe));
885        guard
886    } else {
887        configure_converse_policy(false, false, &config.root, None, false)?;
888        blyte_agent::tools::set_blyte_tool(None);
889        None
890    };
891    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
892    // 1. Initialize LLM provider from environment credentials or model specification.
893    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
894    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
895        Ok(p) => p,
896        Err(blyte_provider::ProviderError::MissingKey(key)) => {
897            return Err(format!(
898                "Provider error: no API key: set {key} in environment"
899            ));
900        }
901        Err(e) => return Err(format!("Provider error: {e}")),
902    };
903
904    let model_id = provider.model_id();
905    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
906        return Err(format!(
907            "--max-cost needs a known price for {model_id}; none is known"
908        ));
909    }
910    state.brief.max_cost_usd = config.max_cost_usd;
911
912    // 2. Select context assembly strategy.
913    let folded = blyte_agent::context::Folded {
914        // Research quotes code read many turns earlier, so it keeps more before folding.
915        budget_tokens: config.fold_budget.unwrap_or(if config.research {
916            RESEARCH_FOLD_BUDGET
917        } else {
918            blyte_agent::context::Folded::default().budget_tokens
919        }),
920    };
921    let conversational = blyte_agent::context::Conversational;
922    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
923        match config.context_strategy.as_str() {
924            "conversational" => &conversational,
925            _ => &folded,
926        };
927
928    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
929    // and `export` carry over). Container files go through a session too. Each falls back to a
930    // process per command if a session cannot start.
931    let local_fs = blyte_agent::fs::LocalFs;
932    let (persistent, session_fs, root) = match &config.container {
933        Some(cid) => (
934            blyte_agent::shell::PersistentShell::container(
935                cid.clone(),
936                PathBuf::from(&config.container_workdir),
937            ),
938            Some(blyte_agent::fs::SessionFs::container(
939                cid.clone(),
940                PathBuf::from(&config.container_workdir),
941            )),
942            PathBuf::from(&config.container_workdir),
943        ),
944        None => {
945            blyte_agent::shell::set_pass_env(config.pass_env.clone());
946            if !config.converse {
947                if let Some(r) = blyte_agent::rules::load(&config.root) {
948                    eprintln!("blyte: repository rules from {}", r.source.display());
949                }
950            }
951            let withheld = blyte_agent::shell::withheld_env();
952            if withheld_notice_is_due(&withheld) {
953                eprintln!(
954                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
955                    withheld.join(", ")
956                );
957            }
958            let shell = build_local_shell(config)?;
959            (shell, None, config.root.clone())
960        }
961    };
962    let shell: &dyn blyte_agent::shell::Shell = &persistent;
963    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
964        Some(f) => f,
965        None => &local_fs,
966    };
967
968    let usage_path = crate::usage_log::default_path();
969    let written = Mutex::new((0u32, blyte_provider::Usage::default()));
970    let runner_on_event = |event: blyte_agent::run::Event<'_>| {
971        if let blyte_agent::run::Event::Turn { usage, .. } = &event {
972            if let Some(path) = &usage_path {
973                let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
974                match crate::usage_log::append(path, &entry) {
975                    Ok(()) => {
976                        let mut w = match written.lock() {
977                            Ok(g) => g,
978                            Err(e) => e.into_inner(),
979                        };
980                        w.0 += 1;
981                        w.1.input += usage.input;
982                        w.1.cached += usage.cached;
983                        w.1.output += usage.output;
984                        w.1.thinking += usage.thinking;
985                    }
986                    Err(err) => eprintln!("warning: usage log: {err}"),
987                }
988            }
989        }
990        on_event(&event);
991    };
992
993    let bg_base_check = match &config.base_check_dir {
994        Some(base_dir)
995            if !blyte_agent::run::gate_steps(&state.brief.verification_cmd).is_empty() =>
996        {
997            let deadline = max_duration.map(|d| std::time::Instant::now() + d);
998            Some(BackgroundBaseCheck::start(
999                config,
1000                state.brief.verification_cmd.clone(),
1001                base_dir.clone(),
1002                deadline,
1003            )?)
1004        }
1005        _ => None,
1006    };
1007    let base_check = if let Some(ref bg) = bg_base_check {
1008        blyte_agent::run::BaseCheck::Polled(bg)
1009    } else if config.base_check {
1010        blyte_agent::run::BaseCheck::BeforeFirstTurn
1011    } else {
1012        blyte_agent::run::BaseCheck::None
1013    };
1014
1015    let runner = blyte_agent::run::Runner {
1016        provider: provider.as_ref(),
1017        shell,
1018        fs,
1019        context: context_strategy,
1020        root,
1021        budget: blyte_agent::run::Budget {
1022            max_turns: config.max_turns as u32,
1023            max_gate_attempts: config.max_gates as u32,
1024            max_duration,
1025        },
1026        rollback: config.rollback,
1027        on_event: Some(&runner_on_event),
1028        research: config.research,
1029        claim_check: config.claim_check,
1030        base_check,
1031    };
1032
1033    let (outcome, report) = runner.run(state);
1034    drop(bg_base_check);
1035
1036    if let Some(path) = &usage_path {
1037        let (written_turns, written_usage) = match written.lock() {
1038            Ok(g) => *g,
1039            Err(e) => *e.into_inner(),
1040        };
1041        let (closing_turns, closing_usage) = match usage_remainder(
1042            report.outcome_turns,
1043            &report.usage,
1044            written_turns,
1045            &written_usage,
1046        ) {
1047            Ok(rem) => rem,
1048            Err(exceeded) => {
1049                for ExceededField {
1050                    field,
1051                    written,
1052                    total,
1053                } in exceeded
1054                {
1055                    eprintln!(
1056                        "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
1057                    );
1058                }
1059                (0, blyte_provider::Usage::default())
1060            }
1061        };
1062        let entry = build_usage_entry(
1063            config,
1064            &model_id,
1065            format!("{outcome:?}").to_lowercase(),
1066            closing_turns,
1067            &closing_usage,
1068        );
1069        if let Err(err) = crate::usage_log::append(path, &entry) {
1070            eprintln!("warning: usage log: {err}");
1071        }
1072    }
1073
1074    if let Some(path) = &config.report {
1075        let mut record = crate::report::RunRecord::from_run(
1076            config,
1077            &model_id,
1078            &outcome,
1079            &report,
1080            state,
1081            started.elapsed(),
1082        );
1083        record.effort = provider.effort();
1084        crate::report::write(path, &record)?;
1085    }
1086    Ok((outcome, report))
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092
1093    #[test]
1094    fn usage_remainder_computes_exact_and_partial_remainders() {
1095        let total = blyte_provider::Usage {
1096            input: 600,
1097            cached: 150,
1098            output: 90,
1099            thinking: 75,
1100        };
1101        let exact = usage_remainder(3, &total, 3, &total).unwrap();
1102        assert_eq!(exact, (0, blyte_provider::Usage::default()));
1103
1104        let written = blyte_provider::Usage {
1105            input: 500,
1106            cached: 100,
1107            output: 80,
1108            thinking: 50,
1109        };
1110        let partial = usage_remainder(3, &total, 2, &written).unwrap();
1111        assert_eq!(
1112            partial,
1113            (
1114                1,
1115                blyte_provider::Usage {
1116                    input: 100,
1117                    cached: 50,
1118                    output: 10,
1119                    thinking: 25,
1120                }
1121            )
1122        );
1123    }
1124
1125    #[test]
1126    fn usage_remainder_reports_exceeding_fields() {
1127        let total = blyte_provider::Usage {
1128            input: 100,
1129            cached: 20,
1130            output: 30,
1131            thinking: 10,
1132        };
1133        let written = blyte_provider::Usage {
1134            input: 120,
1135            cached: 20,
1136            output: 35,
1137            thinking: 10,
1138        };
1139        let err = usage_remainder(2, &total, 3, &written).unwrap_err();
1140        assert_eq!(
1141            err,
1142            vec![
1143                ExceededField {
1144                    field: "turns",
1145                    written: 3,
1146                    total: 2,
1147                },
1148                ExceededField {
1149                    field: "input",
1150                    written: 120,
1151                    total: 100,
1152                },
1153                ExceededField {
1154                    field: "output",
1155                    written: 35,
1156                    total: 30,
1157                },
1158            ]
1159        );
1160    }
1161
1162    fn test_task_config(root: &Path, report: Option<PathBuf>, model: Option<String>) -> TaskConfig {
1163        TaskConfig {
1164            prompt: "test".to_string(),
1165            gate: Some("true".to_string()),
1166            context_strategy: "folded".to_string(),
1167            model,
1168            container: None,
1169            max_turns: 10,
1170            max_gates: 3,
1171            rollback: false,
1172            root: root.to_path_buf(),
1173            container_workdir: "/workspace".to_string(),
1174            max_seconds: Some(10),
1175            max_cost_usd: None,
1176            report,
1177            fold_budget: None,
1178            sandbox: "off".to_string(),
1179            network: "on".to_string(),
1180            allow_read: Vec::new(),
1181            pass_env: Vec::new(),
1182            research: false,
1183            claim_check: false,
1184            base_check: false,
1185            base_check_dir: None,
1186            converse: false,
1187            dispatch_cmd: None,
1188        }
1189    }
1190
1191    #[test]
1192    fn watchdog_report_write_failure_names_path_and_model_id_is_never_empty() {
1193        let dir = tempfile::tempdir().unwrap();
1194        let report_dir = dir.path().join("unwritable.report.json");
1195        std::fs::create_dir_all(&report_dir).unwrap();
1196
1197        let cfg = test_task_config(dir.path(), Some(report_dir.clone()), None);
1198        let progress = Progress {
1199            turns: 2,
1200            gate_attempts: 1,
1201            in_gate: false,
1202            gate_wait_ms: 0,
1203            usage: blyte_provider::Usage {
1204                input: 1000,
1205                cached: 0,
1206                output: 500,
1207                thinking: 0,
1208            },
1209        };
1210        let mut err_buf = Vec::new();
1211        let err = write_watchdog_report(
1212            &cfg,
1213            &progress,
1214            "stopped past --max-seconds",
1215            std::time::Duration::from_secs(5),
1216            |_| Err("missing API key".to_string()),
1217            &mut err_buf,
1218        )
1219        .expect_err("writing watchdog report to a directory must fail");
1220
1221        assert!(
1222            err.contains(&report_dir.display().to_string()),
1223            "write error must name report path, got: {err}"
1224        );
1225        let warning = String::from_utf8(err_buf).unwrap();
1226        assert!(
1227            warning.contains("missing API key"),
1228            "provider resolution error must be logged, got: {warning}"
1229        );
1230
1231        let ok_report = dir.path().join("ok.report.json");
1232        let ok_cfg = test_task_config(dir.path(), Some(ok_report.clone()), None);
1233        let mut ok_err = Vec::new();
1234        let rec = write_watchdog_report(
1235            &ok_cfg,
1236            &progress,
1237            "stopped past --max-seconds",
1238            std::time::Duration::from_secs(5),
1239            |_| Ok("gemini-3.8-flash-high".to_string()),
1240            &mut ok_err,
1241        )
1242        .expect("writing watchdog report to file must succeed")
1243        .expect("record must be returned");
1244
1245        assert_eq!(rec.model_id.as_deref(), Some("gemini-3.8-flash-high"));
1246        assert!(rec.cost_usd.is_some());
1247
1248        let fallback_report = dir.path().join("fallback.report.json");
1249        let fallback_cfg = test_task_config(dir.path(), Some(fallback_report), None);
1250        let mut fallback_err = Vec::new();
1251        let fallback_rec = write_watchdog_report(
1252            &fallback_cfg,
1253            &progress,
1254            "stopped past --max-seconds",
1255            std::time::Duration::from_secs(5),
1256            |_| Err("no provider".to_string()),
1257            &mut fallback_err,
1258        )
1259        .expect("writing watchdog report must succeed")
1260        .expect("record must be returned");
1261
1262        assert_ne!(fallback_rec.model_id.as_deref(), Some(""));
1263        assert_eq!(fallback_rec.model_id, None);
1264        assert!(String::from_utf8(fallback_err)
1265            .unwrap()
1266            .contains("no provider"));
1267    }
1268}