Skip to main content

blyte_cli/
task_runner.rs

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