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