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