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            blyte_agent::shell::PersistentShell::local_sandboxed(config.root.clone(), profile)
364        } else {
365            eprintln!("warning: sandbox unavailable; running unsandboxed");
366            blyte_agent::shell::PersistentShell::local(config.root.clone())
367        }
368    } else {
369        blyte_agent::shell::PersistentShell::local(config.root.clone())
370    }
371}
372
373/// Validates network configuration against the environment and active flags.
374///
375/// Refuses `--network=off` when running with `--container`, when `--sandbox=off`,
376/// when the sandbox is unavailable, or on Linux when `landlock_abi() < 4`.
377pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
378    if config.network == "off" {
379        if config.container.is_some() {
380            return Err(
381                "--network=off is not supported with --container; set the container's network instead"
382                    .into(),
383            );
384        }
385        if config.sandbox != "on" {
386            return Err("--network=off needs the sandbox".into());
387        }
388        #[cfg(target_os = "linux")]
389        if blyte_agent::sandbox::landlock_abi() < 4 {
390            return Err("--network=off on Linux needs Linux 6.7 or later".into());
391        }
392        if !blyte_agent::sandbox::available() {
393            return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
394        }
395    }
396    Ok(())
397}
398
399/// Executes an autonomous solver run using the provided task configuration and live stdout.
400///
401/// Configures the AI provider, context strategy, execution environment (local or container),
402/// and deterministic gate loop, printing live event progress as turns execute.
403///
404/// # Arguments
405///
406/// * `config` - Parameters governing prompt, budgets, gate verification, and environment.
407///
408/// # Returns
409///
410/// Returns `Ok((Outcome, RunReport))` containing final completion status and metrics,
411/// or an `Err(String)` describing initialization failure.
412pub fn run_task(
413    config: TaskConfig,
414) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
415    let started = std::time::Instant::now();
416    let progress = Arc::new(Mutex::new(Progress::default()));
417    if let Some(s) = config.max_seconds {
418        // BLYTE_WATCHDOG_GRACE_SECS exists for tests.
419        let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
420            .ok()
421            .and_then(|v| v.trim().parse().ok())
422            .unwrap_or(30);
423        let watchdog_config = config.clone();
424        let watchdog_progress = Arc::clone(&progress);
425        std::thread::spawn(move || {
426            loop {
427                let wait_ms = match watchdog_progress.lock() {
428                    Ok(g) => g.gate_wait_ms,
429                    Err(e) => e.into_inner().gate_wait_ms,
430                };
431                let deadline = started
432                    + std::time::Duration::from_secs(s.saturating_add(grace_secs))
433                    + std::time::Duration::from_millis(wait_ms);
434                match deadline.checked_duration_since(std::time::Instant::now()) {
435                    Some(remaining) if !remaining.is_zero() => {
436                        std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
437                    }
438                    _ => break,
439                }
440            }
441            let p = match watchdog_progress.lock() {
442                Ok(g) => *g,
443                Err(e) => *e.into_inner(),
444            };
445            let msg = if p.in_gate {
446                format!(
447                    "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
448                    p.gate_attempts
449                )
450            } else {
451                format!(
452                    "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
453                    p.turns
454                )
455            };
456            if let Some(path) = &watchdog_config.report {
457                let mut record =
458                    crate::report::RunRecord::from_error(&watchdog_config, &msg, started.elapsed());
459                record.turns = p.turns;
460                record.gate_attempts = p.gate_attempts;
461                record.usage = crate::report::UsageRecord {
462                    input: p.usage.input,
463                    cached: p.usage.cached,
464                    output: p.usage.output,
465                    thinking: p.usage.thinking,
466                };
467                let model_id = blyte_provider::resolve_provider(watchdog_config.model.as_deref())
468                    .map(|pr| pr.model_id())
469                    .ok()
470                    .or_else(|| watchdog_config.model.clone())
471                    .unwrap_or_default();
472                record.cost_usd = blyte_provider::pricing(&model_id).map(|pr| pr.cost(&p.usage));
473                let _ = crate::report::write(path, &record);
474            }
475            eprintln!("blyte: {msg}");
476            std::process::exit(1);
477        });
478    }
479    let verification_cmd = config.gate.as_deref().unwrap_or("");
480    let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
481    state.orchestrator.max_cost_usd = config.max_cost_usd;
482    let mut stdout = std::io::stdout();
483    let result =
484        run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
485    // The loop writes its own report; this covers a run that never reached it (e.g. no API
486    // key), so a caller always finds one. An absent report would read as a crash.
487    if let (Err(e), Some(path)) = (&result, &config.report) {
488        crate::report::write(
489            path,
490            &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
491        )?;
492    }
493    result
494}
495
496/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`.
497///
498/// Preserves session mutations (epistemic ledger, patches, attempts) directly in the provided `state`.
499///
500/// # Arguments
501///
502/// * `config` - Execution parameters.
503/// * `state` - The mutable session state to advance.
504/// * `writer` - Stream writer sink for formatted events.
505///
506/// # Returns
507///
508/// Returns `Ok((Outcome, RunReport))` or an `Err(String)` describing failure.
509pub fn run_task_with_state_and_writer<W: Write>(
510    config: &TaskConfig,
511    state: &mut blyte_agent::state::State,
512    writer: &mut W,
513) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
514    let progress = Arc::new(Mutex::new(Progress::default()));
515    run_task_with_state_writer_and_progress(config, state, writer, progress)
516}
517
518/// Executes an autonomous solver run against an existing mutable `State`, passing every raw event
519/// directly to `on_event` without formatting lines to a writer.
520pub fn run_task_with_state_and_events(
521    config: &TaskConfig,
522    state: &mut blyte_agent::state::State,
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, None, &|event| on_event(event))
526}
527
528/// Executes an autonomous solver run with an explicit approver override (used by the surface).
529pub fn run_task_with_approver(
530    config: &TaskConfig,
531    state: &mut blyte_agent::state::State,
532    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
533    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
534) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
535    run_task_with_event_callback(config, state, approver, &|event| on_event(event))
536}
537
538/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
539/// and updating the shared `progress` record.
540pub fn run_task_with_state_writer_and_progress<W: Write>(
541    config: &TaskConfig,
542    state: &mut blyte_agent::state::State,
543    writer: &mut W,
544    progress: Arc<Mutex<Progress>>,
545) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
546    let writer_mutex = Mutex::new(writer);
547    let on_event = |event: &blyte_agent::run::Event<'_>| {
548        {
549            let mut p = match progress.lock() {
550                Ok(g) => g,
551                Err(e) => e.into_inner(),
552            };
553            match event {
554                blyte_agent::run::Event::Turn { n, usage, .. } => {
555                    p.turns = *n;
556                    p.usage.input += usage.input;
557                    p.usage.cached += usage.cached;
558                    p.usage.output += usage.output;
559                    p.usage.thinking += usage.thinking;
560                    p.in_gate = false;
561                }
562                blyte_agent::run::Event::GateStart { attempt } => {
563                    p.gate_attempts = *attempt;
564                    p.in_gate = true;
565                }
566                blyte_agent::run::Event::GateSlotWait { ms } => {
567                    p.gate_wait_ms += ms;
568                }
569                blyte_agent::run::Event::Gate { .. } => {
570                    p.in_gate = false;
571                }
572                _ => {}
573            }
574        }
575        let line = crate::repl::format_event(event);
576        if !line.is_empty() {
577            if let Ok(mut w) = writer_mutex.lock() {
578                let _ = writeln!(w, "{line}");
579            }
580        }
581    };
582    run_task_with_event_callback(config, state, None, &on_event)
583}
584
585fn build_usage_entry(
586    config: &TaskConfig,
587    model_id: &str,
588    outcome: String,
589    turns: u32,
590    usage: &blyte_provider::Usage,
591) -> crate::usage_log::Entry {
592    crate::usage_log::Entry {
593        ts: std::time::SystemTime::now()
594            .duration_since(std::time::UNIX_EPOCH)
595            .map(|d| d.as_secs())
596            .unwrap_or(0),
597        repo: crate::usage_log::repo_of(&config.root),
598        session: crate::usage_log::session_from(
599            std::env::var("BLYTE_SESSION").ok(),
600            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
601        ),
602        dispatch: std::env::var("BLYTE_DISPATCH_ID")
603            .ok()
604            .filter(|s| !s.is_empty()),
605        research: config.research,
606        model: model_id.to_string(),
607        outcome,
608        turns,
609        input: usage.input,
610        cached: usage.cached,
611        output: usage.output,
612        thinking: usage.thinking,
613        cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
614    }
615}
616
617#[derive(Debug, PartialEq, Eq)]
618struct ExceededField {
619    field: &'static str,
620    written: u64,
621    total: u64,
622}
623
624fn usage_remainder(
625    total_turns: u32,
626    total_usage: &blyte_provider::Usage,
627    written_turns: u32,
628    written_usage: &blyte_provider::Usage,
629) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
630    let mut exceeded = Vec::new();
631    if written_turns > total_turns {
632        exceeded.push(ExceededField {
633            field: "turns",
634            written: u64::from(written_turns),
635            total: u64::from(total_turns),
636        });
637    }
638    if written_usage.input > total_usage.input {
639        exceeded.push(ExceededField {
640            field: "input",
641            written: written_usage.input,
642            total: total_usage.input,
643        });
644    }
645    if written_usage.cached > total_usage.cached {
646        exceeded.push(ExceededField {
647            field: "cached",
648            written: written_usage.cached,
649            total: total_usage.cached,
650        });
651    }
652    if written_usage.output > total_usage.output {
653        exceeded.push(ExceededField {
654            field: "output",
655            written: written_usage.output,
656            total: total_usage.output,
657        });
658    }
659    if written_usage.thinking > total_usage.thinking {
660        exceeded.push(ExceededField {
661            field: "thinking",
662            written: written_usage.thinking,
663            total: total_usage.thinking,
664        });
665    }
666    if !exceeded.is_empty() {
667        return Err(exceeded);
668    }
669    Ok((
670        total_turns - written_turns,
671        blyte_provider::Usage {
672            input: total_usage.input - written_usage.input,
673            cached: total_usage.cached - written_usage.cached,
674            output: total_usage.output - written_usage.output,
675            thinking: total_usage.thinking - written_usage.thinking,
676        },
677    ))
678}
679
680fn run_task_with_event_callback(
681    config: &TaskConfig,
682    state: &mut blyte_agent::state::State,
683    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
684    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
685) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
686    check_network_mode(config)?;
687    let started = std::time::Instant::now();
688    if config.orchestrate {
689        if std::env::var("BLYTE_SESSION")
690            .map(|v| v.is_empty())
691            .unwrap_or(true)
692        {
693            let now_secs = std::time::SystemTime::now()
694                .duration_since(std::time::UNIX_EPOCH)
695                .map(|d| d.as_secs())
696                .unwrap_or(0);
697            let id = crate::repl::new_session_id(now_secs, std::process::id());
698            std::env::set_var("BLYTE_SESSION", &id);
699        }
700        let sandbox_on = config.sandbox == "on";
701        let allowed_count = configure_orchestrate_policy(
702            true,
703            sandbox_on,
704            &config.root,
705            approver,
706            state.runtime.conversation.is_some(),
707        )?;
708        if state.orchestrator.instructions.is_none() {
709            let lines = crate::orchestrator_text::set_state_instructions(
710                state,
711                config.dispatch_cmd.is_some(),
712                &config.root,
713                sandbox_on,
714                allowed_count,
715            )?;
716            if state.runtime.conversation.is_none() {
717                for line in &lines {
718                    eprintln!("blyte: {line}");
719                }
720            }
721        }
722        let exe = std::env::current_exe()
723            .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
724        blyte_agent::tools::set_blyte_tool(Some(exe));
725    } else {
726        configure_orchestrate_policy(false, false, &config.root, None, false)?;
727        blyte_agent::tools::set_blyte_tool(None);
728    }
729    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
730    // 1. Initialize LLM provider from environment credentials or model specification.
731    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
732    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
733        Ok(p) => p,
734        Err(blyte_provider::ProviderError::MissingKey(key)) => {
735            return Err(format!(
736                "Provider error: no API key: set {key} in environment"
737            ));
738        }
739        Err(e) => return Err(format!("Provider error: {e}")),
740    };
741
742    let model_id = provider.model_id();
743    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
744        return Err(format!(
745            "--max-cost needs a known price for {model_id}; none is known"
746        ));
747    }
748    state.orchestrator.max_cost_usd = config.max_cost_usd;
749
750    // 2. Select context assembly strategy.
751    let folded = blyte_agent::context::Folded {
752        // Research quotes code read many turns earlier, so it keeps more before folding.
753        budget_tokens: config.fold_budget.unwrap_or(if config.research {
754            RESEARCH_FOLD_BUDGET
755        } else {
756            blyte_agent::context::Folded::default().budget_tokens
757        }),
758    };
759    let conversational = blyte_agent::context::Conversational;
760    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
761        match config.context_strategy.as_str() {
762            "conversational" => &conversational,
763            _ => &folded,
764        };
765
766    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
767    // and `export` carry over). Container files go through a session too. Each falls back to a
768    // process per command if a session cannot start.
769    let local_fs = blyte_agent::fs::LocalFs;
770    let (persistent, session_fs, root) = match &config.container {
771        Some(cid) => (
772            blyte_agent::shell::PersistentShell::container(
773                cid.clone(),
774                PathBuf::from(&config.container_workdir),
775            ),
776            Some(blyte_agent::fs::SessionFs::container(
777                cid.clone(),
778                PathBuf::from(&config.container_workdir),
779            )),
780            PathBuf::from(&config.container_workdir),
781        ),
782        None => {
783            blyte_agent::shell::set_pass_env(config.pass_env.clone());
784            if !config.orchestrate {
785                if let Some(r) = blyte_agent::rules::load(&config.root) {
786                    eprintln!("blyte: repository rules from {}", r.source.display());
787                }
788            }
789            let withheld = blyte_agent::shell::withheld_env();
790            if !withheld.is_empty() {
791                eprintln!(
792                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
793                    withheld.join(", ")
794                );
795            }
796            let shell = build_local_shell(config);
797            (shell, None, config.root.clone())
798        }
799    };
800    let shell: &dyn blyte_agent::shell::Shell = &persistent;
801    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
802        Some(f) => f,
803        None => &local_fs,
804    };
805
806    let usage_path = crate::usage_log::default_path();
807    let written = Mutex::new((0u32, blyte_provider::Usage::default()));
808    let runner_on_event = |event: blyte_agent::run::Event<'_>| {
809        if let blyte_agent::run::Event::Turn { usage, .. } = &event {
810            if let Some(path) = &usage_path {
811                let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
812                match crate::usage_log::append(path, &entry) {
813                    Ok(()) => {
814                        let mut w = match written.lock() {
815                            Ok(g) => g,
816                            Err(e) => e.into_inner(),
817                        };
818                        w.0 += 1;
819                        w.1.input += usage.input;
820                        w.1.cached += usage.cached;
821                        w.1.output += usage.output;
822                        w.1.thinking += usage.thinking;
823                    }
824                    Err(err) => eprintln!("warning: usage log: {err}"),
825                }
826            }
827        }
828        on_event(&event);
829    };
830
831    let bg_base_check = match &config.base_check_dir {
832        Some(base_dir)
833            if !blyte_agent::run::gate_steps(&state.orchestrator.verification_cmd).is_empty() =>
834        {
835            let deadline = config
836                .max_seconds
837                .map(|s| std::time::Instant::now() + std::time::Duration::from_secs(s));
838            Some(BackgroundBaseCheck::start(
839                config,
840                state.orchestrator.verification_cmd.clone(),
841                base_dir.clone(),
842                deadline,
843            ))
844        }
845        _ => None,
846    };
847    let base_check = if let Some(ref bg) = bg_base_check {
848        blyte_agent::run::BaseCheck::Polled(bg)
849    } else if config.base_check {
850        blyte_agent::run::BaseCheck::BeforeFirstTurn
851    } else {
852        blyte_agent::run::BaseCheck::None
853    };
854
855    let runner = blyte_agent::run::Runner {
856        provider: provider.as_ref(),
857        shell,
858        fs,
859        context: context_strategy,
860        root,
861        budget: blyte_agent::run::Budget {
862            max_turns: config.max_turns as u32,
863            max_gate_attempts: config.max_gates as u32,
864            max_duration: config.max_seconds.map(std::time::Duration::from_secs),
865        },
866        rollback: config.rollback,
867        on_event: Some(&runner_on_event),
868        research: config.research,
869        claim_check: config.claim_check,
870        base_check,
871    };
872
873    let (outcome, report) = runner.run(state);
874    drop(bg_base_check);
875
876    if let Some(path) = &usage_path {
877        let (written_turns, written_usage) = match written.lock() {
878            Ok(g) => *g,
879            Err(e) => *e.into_inner(),
880        };
881        let (closing_turns, closing_usage) = match usage_remainder(
882            report.outcome_turns,
883            &report.usage,
884            written_turns,
885            &written_usage,
886        ) {
887            Ok(rem) => rem,
888            Err(exceeded) => {
889                for ExceededField {
890                    field,
891                    written,
892                    total,
893                } in exceeded
894                {
895                    eprintln!(
896                        "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
897                    );
898                }
899                (0, blyte_provider::Usage::default())
900            }
901        };
902        let entry = build_usage_entry(
903            config,
904            &model_id,
905            format!("{outcome:?}").to_lowercase(),
906            closing_turns,
907            &closing_usage,
908        );
909        if let Err(err) = crate::usage_log::append(path, &entry) {
910            eprintln!("warning: usage log: {err}");
911        }
912    }
913
914    if let Some(path) = &config.report {
915        let mut record = crate::report::RunRecord::from_run(
916            config,
917            &model_id,
918            &outcome,
919            &report,
920            state,
921            started.elapsed(),
922        );
923        record.effort = provider.effort();
924        crate::report::write(path, &record)?;
925    }
926    Ok((outcome, report))
927}
928
929#[cfg(test)]
930mod tests {
931    use super::*;
932
933    #[test]
934    fn usage_remainder_computes_exact_and_partial_remainders() {
935        let total = blyte_provider::Usage {
936            input: 600,
937            cached: 150,
938            output: 90,
939            thinking: 75,
940        };
941        let exact = usage_remainder(3, &total, 3, &total).unwrap();
942        assert_eq!(exact, (0, blyte_provider::Usage::default()));
943
944        let written = blyte_provider::Usage {
945            input: 500,
946            cached: 100,
947            output: 80,
948            thinking: 50,
949        };
950        let partial = usage_remainder(3, &total, 2, &written).unwrap();
951        assert_eq!(
952            partial,
953            (
954                1,
955                blyte_provider::Usage {
956                    input: 100,
957                    cached: 50,
958                    output: 10,
959                    thinking: 25,
960                }
961            )
962        );
963    }
964
965    #[test]
966    fn usage_remainder_reports_exceeding_fields() {
967        let total = blyte_provider::Usage {
968            input: 100,
969            cached: 20,
970            output: 30,
971            thinking: 10,
972        };
973        let written = blyte_provider::Usage {
974            input: 120,
975            cached: 20,
976            output: 35,
977            thinking: 10,
978        };
979        let err = usage_remainder(2, &total, 3, &written).unwrap_err();
980        assert_eq!(
981            err,
982            vec![
983                ExceededField {
984                    field: "turns",
985                    written: 3,
986                    total: 2,
987                },
988                ExceededField {
989                    field: "input",
990                    written: 120,
991                    total: 100,
992                },
993                ExceededField {
994                    field: "output",
995                    written: 35,
996                    total: 30,
997                },
998            ]
999        );
1000    }
1001}