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