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    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
526    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
527}
528
529pub fn run_task_with_state_and_max_duration(
530    config: &TaskConfig,
531    state: &mut blyte_agent::state::State,
532    max_duration: Option<std::time::Duration>,
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, None, max_duration, &|event| on_event(event))
536}
537
538/// Executes an autonomous solver run with an explicit approver override (used by the surface).
539pub fn run_task_with_approver(
540    config: &TaskConfig,
541    state: &mut blyte_agent::state::State,
542    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
543    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
544) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
545    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
546    run_task_with_event_callback(config, state, approver, max_duration, &|event| {
547        on_event(event)
548    })
549}
550
551/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
552/// and updating the shared `progress` record.
553pub fn run_task_with_state_writer_and_progress<W: Write>(
554    config: &TaskConfig,
555    state: &mut blyte_agent::state::State,
556    writer: &mut W,
557    progress: Arc<Mutex<Progress>>,
558) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
559    let writer_mutex = Mutex::new(writer);
560    let on_event = |event: &blyte_agent::run::Event<'_>| {
561        {
562            let mut p = match progress.lock() {
563                Ok(g) => g,
564                Err(e) => e.into_inner(),
565            };
566            match event {
567                blyte_agent::run::Event::Turn { n, usage, .. } => {
568                    p.turns = *n;
569                    p.usage.input += usage.input;
570                    p.usage.cached += usage.cached;
571                    p.usage.output += usage.output;
572                    p.usage.thinking += usage.thinking;
573                    p.in_gate = false;
574                }
575                blyte_agent::run::Event::GateStart { attempt } => {
576                    p.gate_attempts = *attempt;
577                    p.in_gate = true;
578                }
579                blyte_agent::run::Event::GateSlotWait { ms } => {
580                    p.gate_wait_ms += ms;
581                }
582                blyte_agent::run::Event::Gate { .. } => {
583                    p.in_gate = false;
584                }
585                _ => {}
586            }
587        }
588        let line = crate::repl::format_event(event);
589        if !line.is_empty() {
590            if let Ok(mut w) = writer_mutex.lock() {
591                let _ = writeln!(w, "{line}");
592            }
593        }
594    };
595    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
596    run_task_with_event_callback(config, state, None, max_duration, &on_event)
597}
598
599fn build_usage_entry(
600    config: &TaskConfig,
601    model_id: &str,
602    outcome: String,
603    turns: u32,
604    usage: &blyte_provider::Usage,
605) -> crate::usage_log::Entry {
606    crate::usage_log::Entry {
607        ts: std::time::SystemTime::now()
608            .duration_since(std::time::UNIX_EPOCH)
609            .map(|d| d.as_secs())
610            .unwrap_or(0),
611        repo: crate::usage_log::repo_of(&config.root),
612        session: crate::usage_log::session_from(
613            std::env::var("BLYTE_SESSION").ok(),
614            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
615        ),
616        dispatch: std::env::var("BLYTE_DISPATCH_ID")
617            .ok()
618            .filter(|s| !s.is_empty()),
619        research: config.research,
620        model: model_id.to_string(),
621        outcome,
622        turns,
623        input: usage.input,
624        cached: usage.cached,
625        output: usage.output,
626        thinking: usage.thinking,
627        cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
628    }
629}
630
631#[derive(Debug, PartialEq, Eq)]
632struct ExceededField {
633    field: &'static str,
634    written: u64,
635    total: u64,
636}
637
638fn usage_remainder(
639    total_turns: u32,
640    total_usage: &blyte_provider::Usage,
641    written_turns: u32,
642    written_usage: &blyte_provider::Usage,
643) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
644    let mut exceeded = Vec::new();
645    if written_turns > total_turns {
646        exceeded.push(ExceededField {
647            field: "turns",
648            written: u64::from(written_turns),
649            total: u64::from(total_turns),
650        });
651    }
652    if written_usage.input > total_usage.input {
653        exceeded.push(ExceededField {
654            field: "input",
655            written: written_usage.input,
656            total: total_usage.input,
657        });
658    }
659    if written_usage.cached > total_usage.cached {
660        exceeded.push(ExceededField {
661            field: "cached",
662            written: written_usage.cached,
663            total: total_usage.cached,
664        });
665    }
666    if written_usage.output > total_usage.output {
667        exceeded.push(ExceededField {
668            field: "output",
669            written: written_usage.output,
670            total: total_usage.output,
671        });
672    }
673    if written_usage.thinking > total_usage.thinking {
674        exceeded.push(ExceededField {
675            field: "thinking",
676            written: written_usage.thinking,
677            total: total_usage.thinking,
678        });
679    }
680    if !exceeded.is_empty() {
681        return Err(exceeded);
682    }
683    Ok((
684        total_turns - written_turns,
685        blyte_provider::Usage {
686            input: total_usage.input - written_usage.input,
687            cached: total_usage.cached - written_usage.cached,
688            output: total_usage.output - written_usage.output,
689            thinking: total_usage.thinking - written_usage.thinking,
690        },
691    ))
692}
693
694fn run_task_with_event_callback(
695    config: &TaskConfig,
696    state: &mut blyte_agent::state::State,
697    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
698    max_duration: Option<std::time::Duration>,
699    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
700) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
701    check_network_mode(config)?;
702    let started = std::time::Instant::now();
703    if config.orchestrate {
704        if std::env::var("BLYTE_SESSION")
705            .map(|v| v.is_empty())
706            .unwrap_or(true)
707        {
708            let now_secs = std::time::SystemTime::now()
709                .duration_since(std::time::UNIX_EPOCH)
710                .map(|d| d.as_secs())
711                .unwrap_or(0);
712            let id = crate::repl::new_session_id(now_secs, std::process::id());
713            std::env::set_var("BLYTE_SESSION", &id);
714        }
715        let sandbox_on = config.sandbox == "on";
716        let allowed_count = configure_orchestrate_policy(
717            true,
718            sandbox_on,
719            &config.root,
720            approver,
721            state.runtime.conversation.is_some(),
722        )?;
723        if state.orchestrator.instructions.is_none() {
724            let lines = crate::orchestrator_text::set_state_instructions(
725                state,
726                config.dispatch_cmd.is_some(),
727                &config.root,
728                sandbox_on,
729                allowed_count,
730            )?;
731            if state.runtime.conversation.is_none() {
732                for line in &lines {
733                    eprintln!("blyte: {line}");
734                }
735            }
736        }
737        let exe = std::env::current_exe()
738            .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
739        blyte_agent::tools::set_blyte_tool(Some(exe));
740    } else {
741        configure_orchestrate_policy(false, false, &config.root, None, false)?;
742        blyte_agent::tools::set_blyte_tool(None);
743    }
744    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
745    // 1. Initialize LLM provider from environment credentials or model specification.
746    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
747    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
748        Ok(p) => p,
749        Err(blyte_provider::ProviderError::MissingKey(key)) => {
750            return Err(format!(
751                "Provider error: no API key: set {key} in environment"
752            ));
753        }
754        Err(e) => return Err(format!("Provider error: {e}")),
755    };
756
757    let model_id = provider.model_id();
758    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
759        return Err(format!(
760            "--max-cost needs a known price for {model_id}; none is known"
761        ));
762    }
763    state.orchestrator.max_cost_usd = config.max_cost_usd;
764
765    // 2. Select context assembly strategy.
766    let folded = blyte_agent::context::Folded {
767        // Research quotes code read many turns earlier, so it keeps more before folding.
768        budget_tokens: config.fold_budget.unwrap_or(if config.research {
769            RESEARCH_FOLD_BUDGET
770        } else {
771            blyte_agent::context::Folded::default().budget_tokens
772        }),
773    };
774    let conversational = blyte_agent::context::Conversational;
775    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
776        match config.context_strategy.as_str() {
777            "conversational" => &conversational,
778            _ => &folded,
779        };
780
781    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
782    // and `export` carry over). Container files go through a session too. Each falls back to a
783    // process per command if a session cannot start.
784    let local_fs = blyte_agent::fs::LocalFs;
785    let (persistent, session_fs, root) = match &config.container {
786        Some(cid) => (
787            blyte_agent::shell::PersistentShell::container(
788                cid.clone(),
789                PathBuf::from(&config.container_workdir),
790            ),
791            Some(blyte_agent::fs::SessionFs::container(
792                cid.clone(),
793                PathBuf::from(&config.container_workdir),
794            )),
795            PathBuf::from(&config.container_workdir),
796        ),
797        None => {
798            blyte_agent::shell::set_pass_env(config.pass_env.clone());
799            if !config.orchestrate {
800                if let Some(r) = blyte_agent::rules::load(&config.root) {
801                    eprintln!("blyte: repository rules from {}", r.source.display());
802                }
803            }
804            let withheld = blyte_agent::shell::withheld_env();
805            if !withheld.is_empty() {
806                eprintln!(
807                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
808                    withheld.join(", ")
809                );
810            }
811            let shell = build_local_shell(config);
812            (shell, None, config.root.clone())
813        }
814    };
815    let shell: &dyn blyte_agent::shell::Shell = &persistent;
816    let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
817        Some(f) => f,
818        None => &local_fs,
819    };
820
821    let usage_path = crate::usage_log::default_path();
822    let written = Mutex::new((0u32, blyte_provider::Usage::default()));
823    let runner_on_event = |event: blyte_agent::run::Event<'_>| {
824        if let blyte_agent::run::Event::Turn { usage, .. } = &event {
825            if let Some(path) = &usage_path {
826                let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
827                match crate::usage_log::append(path, &entry) {
828                    Ok(()) => {
829                        let mut w = match written.lock() {
830                            Ok(g) => g,
831                            Err(e) => e.into_inner(),
832                        };
833                        w.0 += 1;
834                        w.1.input += usage.input;
835                        w.1.cached += usage.cached;
836                        w.1.output += usage.output;
837                        w.1.thinking += usage.thinking;
838                    }
839                    Err(err) => eprintln!("warning: usage log: {err}"),
840                }
841            }
842        }
843        on_event(&event);
844    };
845
846    let bg_base_check = match &config.base_check_dir {
847        Some(base_dir)
848            if !blyte_agent::run::gate_steps(&state.orchestrator.verification_cmd).is_empty() =>
849        {
850            let deadline = max_duration.map(|d| std::time::Instant::now() + d);
851            Some(BackgroundBaseCheck::start(
852                config,
853                state.orchestrator.verification_cmd.clone(),
854                base_dir.clone(),
855                deadline,
856            ))
857        }
858        _ => None,
859    };
860    let base_check = if let Some(ref bg) = bg_base_check {
861        blyte_agent::run::BaseCheck::Polled(bg)
862    } else if config.base_check {
863        blyte_agent::run::BaseCheck::BeforeFirstTurn
864    } else {
865        blyte_agent::run::BaseCheck::None
866    };
867
868    let runner = blyte_agent::run::Runner {
869        provider: provider.as_ref(),
870        shell,
871        fs,
872        context: context_strategy,
873        root,
874        budget: blyte_agent::run::Budget {
875            max_turns: config.max_turns as u32,
876            max_gate_attempts: config.max_gates as u32,
877            max_duration,
878        },
879        rollback: config.rollback,
880        on_event: Some(&runner_on_event),
881        research: config.research,
882        claim_check: config.claim_check,
883        base_check,
884    };
885
886    let (outcome, report) = runner.run(state);
887    drop(bg_base_check);
888
889    if let Some(path) = &usage_path {
890        let (written_turns, written_usage) = match written.lock() {
891            Ok(g) => *g,
892            Err(e) => *e.into_inner(),
893        };
894        let (closing_turns, closing_usage) = match usage_remainder(
895            report.outcome_turns,
896            &report.usage,
897            written_turns,
898            &written_usage,
899        ) {
900            Ok(rem) => rem,
901            Err(exceeded) => {
902                for ExceededField {
903                    field,
904                    written,
905                    total,
906                } in exceeded
907                {
908                    eprintln!(
909                        "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
910                    );
911                }
912                (0, blyte_provider::Usage::default())
913            }
914        };
915        let entry = build_usage_entry(
916            config,
917            &model_id,
918            format!("{outcome:?}").to_lowercase(),
919            closing_turns,
920            &closing_usage,
921        );
922        if let Err(err) = crate::usage_log::append(path, &entry) {
923            eprintln!("warning: usage log: {err}");
924        }
925    }
926
927    if let Some(path) = &config.report {
928        let mut record = crate::report::RunRecord::from_run(
929            config,
930            &model_id,
931            &outcome,
932            &report,
933            state,
934            started.elapsed(),
935        );
936        record.effort = provider.effort();
937        crate::report::write(path, &record)?;
938    }
939    Ok((outcome, report))
940}
941
942#[cfg(test)]
943mod tests {
944    use super::*;
945
946    #[test]
947    fn usage_remainder_computes_exact_and_partial_remainders() {
948        let total = blyte_provider::Usage {
949            input: 600,
950            cached: 150,
951            output: 90,
952            thinking: 75,
953        };
954        let exact = usage_remainder(3, &total, 3, &total).unwrap();
955        assert_eq!(exact, (0, blyte_provider::Usage::default()));
956
957        let written = blyte_provider::Usage {
958            input: 500,
959            cached: 100,
960            output: 80,
961            thinking: 50,
962        };
963        let partial = usage_remainder(3, &total, 2, &written).unwrap();
964        assert_eq!(
965            partial,
966            (
967                1,
968                blyte_provider::Usage {
969                    input: 100,
970                    cached: 50,
971                    output: 10,
972                    thinking: 25,
973                }
974            )
975        );
976    }
977
978    #[test]
979    fn usage_remainder_reports_exceeding_fields() {
980        let total = blyte_provider::Usage {
981            input: 100,
982            cached: 20,
983            output: 30,
984            thinking: 10,
985        };
986        let written = blyte_provider::Usage {
987            input: 120,
988            cached: 20,
989            output: 35,
990            thinking: 10,
991        };
992        let err = usage_remainder(2, &total, 3, &written).unwrap_err();
993        assert_eq!(
994            err,
995            vec![
996                ExceededField {
997                    field: "turns",
998                    written: 3,
999                    total: 2,
1000                },
1001                ExceededField {
1002                    field: "input",
1003                    written: 120,
1004                    total: 100,
1005                },
1006                ExceededField {
1007                    field: "output",
1008                    written: 35,
1009                    total: 30,
1010                },
1011            ]
1012        );
1013    }
1014}