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