use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex};
pub const RESEARCH_FOLD_BUDGET: usize = 180_000;
#[derive(Debug, Default, Clone, Copy)]
pub struct Progress {
pub turns: u32,
pub gate_attempts: u32,
pub in_gate: bool,
pub gate_wait_ms: u64,
pub usage: blyte_provider::Usage,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InPlace {
pub before_dir: PathBuf,
pub manifest: PathBuf,
}
#[derive(Debug, Clone)]
pub struct TaskConfig {
pub prompt: String,
pub gate: Option<String>,
pub context_strategy: String,
pub model: Option<String>,
pub container: Option<String>,
pub max_turns: usize,
pub max_gates: usize,
pub rollback: bool,
pub root: PathBuf,
pub container_workdir: String,
pub max_seconds: Option<u64>,
pub max_cost_usd: Option<f64>,
pub report: Option<PathBuf>,
pub fold_budget: Option<usize>,
pub sandbox: String,
pub network: String,
pub allow_read: Vec<PathBuf>,
pub pass_env: Vec<String>,
pub research: bool,
pub claim_check: bool,
pub base_check: bool,
pub base_check_dir: Option<PathBuf>,
pub converse: bool,
pub dispatch_cmd: Option<String>,
pub in_place: Option<InPlace>,
}
impl From<&crate::cli::Cli> for TaskConfig {
fn from(cli: &crate::cli::Cli) -> Self {
blyte_agent::tools::set_read_roots(cli.read_roots.clone());
let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let network = match &cli.network {
Some(v) => v.clone(),
None if cli.converse && cli.sandbox == "on" && cli.container.is_none() => "off".into(),
None => "on".into(),
};
let in_place = match (&cli.snapshot_dir, &cli.snapshot_manifest) {
(Some(before_dir), Some(manifest)) => Some(InPlace {
before_dir: before_dir.clone(),
manifest: manifest.clone(),
}),
_ => None,
};
Self {
prompt: cli.prompt.clone().unwrap_or_default(),
gate: cli.gate.clone(),
context_strategy: cli.context.clone(),
model: cli.model.clone(),
container: cli.container.clone(),
max_turns: cli.max_turns,
max_gates: cli.max_gates,
rollback: cli.rollback && in_place.is_none(),
root,
container_workdir: cli.container_workdir.clone(),
max_seconds: cli.max_seconds,
max_cost_usd: cli.max_cost_usd,
report: cli.report.clone(),
fold_budget: cli.fold_budget,
sandbox: cli.sandbox.clone(),
network,
allow_read: cli.allow_read.clone(),
pass_env: cli.pass_env.clone(),
research: cli.research,
claim_check: cli.claim_check,
base_check: cli.base_check,
base_check_dir: cli.base_check_dir.clone(),
converse: cli.converse,
dispatch_cmd: cli.dispatch_cmd.clone(),
in_place,
}
}
}
struct TempDirGuard(Option<PathBuf>);
impl Drop for TempDirGuard {
fn drop(&mut self) {
if let Some(ref path) = self.0 {
let _ = std::fs::remove_dir_all(path);
}
}
}
pub fn build_sandbox_profile(config: &TaskConfig) -> Result<blyte_agent::sandbox::Profile, String> {
Ok(build_sandbox_for_root(config, &config.root)?.0)
}
fn build_sandbox_for_root(
config: &TaskConfig,
root: &Path,
) -> Result<(blyte_agent::sandbox::Profile, Option<PathBuf>), String> {
if config.converse || config.in_place.is_some() {
let sandbox = blyte_agent::sandbox::conversation_sandbox_net(
root,
&config.allow_read,
config.network == "on",
)?;
Ok((sandbox.profile, sandbox.tmpdir))
} else {
Ok((
blyte_agent::sandbox::default_profile_net(
root,
&config.allow_read,
config.network == "on",
),
None,
))
}
}
pub struct ConversePolicy {
pub allowed_count: usize,
pub private_tmpdir: Option<PathBuf>,
}
pub fn configure_converse_policy_with_paths(
converse: bool,
sandbox_on: bool,
root: &Path,
approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
has_conversation: bool,
) -> Result<ConversePolicy, String> {
if !converse || !sandbox_on {
blyte_agent::tools::set_write_scope(None);
blyte_agent::tools::set_approval(None);
return Ok(ConversePolicy {
allowed_count: 0,
private_tmpdir: None,
});
}
let is_repo = crate::serve::is_repository(root)?;
let paths = blyte_agent::sandbox::conversation_paths(root)?;
let mut tmp_cleanup = TempDirGuard(if paths.created_tmpdir {
paths.tmpdir.clone()
} else {
None
});
let (mut allowed, edit_worktrees) = if is_repo {
let tasks_dir = blyte_agent::sandbox::conversation_tasks_dir(root);
std::fs::create_dir_all(&tasks_dir)
.map_err(|e| format!("cannot create {}: {e}", tasks_dir.display()))?;
let tasks_canon = tasks_dir
.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", tasks_dir.display()))?;
let edit_worktrees = tasks_canon
.parent()
.map(|p| {
p.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", p.display()))
})
.transpose()?;
(vec![tasks_canon], edit_worktrees)
} else {
(Vec::new(), None)
};
for dir in paths.allowed {
match dir.canonicalize() {
Ok(canon) => {
if !allowed.contains(&canon) {
allowed.push(canon);
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("cannot canonicalize {}: {e}", dir.display())),
}
}
blyte_agent::tools::set_write_scope(Some(blyte_agent::tools::WriteScope {
allowed,
edit_worktrees,
}));
let rules = crate::approval_file::load()?;
let allowed_count = rules.len();
let approver: Arc<dyn blyte_agent::approval::Approver> = match approver {
Some(a) => a,
None if has_conversation => Arc::new(crate::tty_approver::TtyApprover),
None => Arc::new(blyte_agent::approval::NoApprover),
};
blyte_agent::tools::set_approval(Some(blyte_agent::approval::ApprovalConfig {
rules,
approver,
}));
tmp_cleanup.0 = None;
Ok(ConversePolicy {
allowed_count,
private_tmpdir: paths.tmpdir,
})
}
pub fn configure_converse_policy(
converse: bool,
sandbox_on: bool,
root: &Path,
approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
has_conversation: bool,
) -> Result<usize, String> {
Ok(configure_converse_policy_with_paths(
converse,
sandbox_on,
root,
approver,
has_conversation,
)?
.allowed_count)
}
struct BackgroundBaseCheckData {
state: blyte_agent::run::BaseCheckState,
elapsed_seconds: Option<f64>,
}
pub struct BackgroundBaseCheck {
shared: Arc<(Mutex<BackgroundBaseCheckData>, Condvar)>,
cancel: Arc<blyte_agent::shell::CancelHandle>,
handle: Mutex<Option<std::thread::JoinHandle<()>>>,
}
impl BackgroundBaseCheck {
pub fn start(
config: &TaskConfig,
gate: String,
base_dir: PathBuf,
deadline: Option<std::time::Instant>,
) -> Result<Self, String> {
let cancel = Arc::new(blyte_agent::shell::CancelHandle::new());
check_in_place_sandbox(config)?;
let shell: Box<dyn blyte_agent::shell::Shell + Send> = match &config.container {
Some(cid) => Box::new(blyte_agent::shell::CancellableContainerShell {
inner: blyte_agent::shell::ContainerShell {
container_id: cid.clone(),
workdir: base_dir.clone(),
},
cancel: Arc::clone(&cancel),
}),
None => {
let inner = if config.sandbox == "on" && blyte_agent::sandbox::available() {
let (profile, tmpdir) = build_sandbox_for_root(config, &base_dir)?;
blyte_agent::shell::LocalShell::sandboxed(profile).with_tmpdir(tmpdir)
} else {
blyte_agent::shell::LocalShell::new()
};
Box::new(blyte_agent::shell::CancellableLocalShell {
inner,
cancel: Arc::clone(&cancel),
})
}
};
let shared = Arc::new((
Mutex::new(BackgroundBaseCheckData {
state: blyte_agent::run::BaseCheckState::Pending,
elapsed_seconds: None,
}),
Condvar::new(),
));
let thread_shared = Arc::clone(&shared);
let thread_cancel = Arc::clone(&cancel);
let join = std::thread::spawn(move || {
let started = std::time::Instant::now();
let mut deadline = deadline;
let result = blyte_agent::run::run_gate_steps_cancellable(
shell.as_ref(),
&gate,
&base_dir,
&[],
&mut deadline,
|_| {},
&std::time::Instant::now,
Some(&thread_cancel),
);
if thread_cancel.is_cancelled() {
return;
}
let elapsed = started.elapsed().as_secs_f64();
let next_state = blyte_agent::run::base_check_state_from_gate(&result);
let (lock, cvar) = &*thread_shared;
let mut guard = match lock.lock() {
Ok(g) => g,
Err(e) => e.into_inner(),
};
guard.state = next_state;
guard.elapsed_seconds = Some(elapsed);
cvar.notify_all();
});
Ok(Self {
shared,
cancel,
handle: Mutex::new(Some(join)),
})
}
}
impl blyte_agent::run::BaseCheckHandle for BackgroundBaseCheck {
fn poll(&self) -> blyte_agent::run::BaseCheckState {
let (lock, _) = &*self.shared;
match lock.lock() {
Ok(g) => g.state.clone(),
Err(e) => e.into_inner().state.clone(),
}
}
fn wait(&self) -> blyte_agent::run::BaseCheckState {
let (lock, cvar) = &*self.shared;
let mut guard = match lock.lock() {
Ok(g) => g,
Err(e) => e.into_inner(),
};
while matches!(guard.state, blyte_agent::run::BaseCheckState::Pending) {
if self.cancel.is_cancelled() {
break;
}
guard = match cvar.wait(guard) {
Ok(g) => g,
Err(e) => e.into_inner(),
};
}
guard.state.clone()
}
fn stop(&self) {
self.cancel.cancel();
let (lock, cvar) = &*self.shared;
let guard = match lock.lock() {
Ok(g) => g,
Err(e) => e.into_inner(),
};
cvar.notify_all();
drop(guard);
let join = match self.handle.lock() {
Ok(mut g) => g.take(),
Err(e) => e.into_inner().take(),
};
if let Some(h) = join {
let _ = h.join();
}
}
fn elapsed_seconds(&self) -> Option<f64> {
let (lock, _) = &*self.shared;
match lock.lock() {
Ok(g) => g.elapsed_seconds,
Err(e) => e.into_inner().elapsed_seconds,
}
}
}
impl Drop for BackgroundBaseCheck {
fn drop(&mut self) {
blyte_agent::run::BaseCheckHandle::stop(self);
}
}
pub fn check_in_place_sandbox(config: &TaskConfig) -> Result<(), String> {
if config.in_place.is_some() {
if config.container.is_some() {
return Err(
"in-place runs need the sandbox: --container cannot be used with in-place runs"
.into(),
);
}
if config.sandbox != "on" {
return Err(format!(
"in-place runs need the sandbox: --sandbox is '{}'",
config.sandbox
));
}
if !blyte_agent::sandbox::available() {
return Err("in-place runs need the sandbox: sandbox is unavailable".into());
}
}
Ok(())
}
pub fn build_local_shell(
config: &TaskConfig,
) -> Result<blyte_agent::shell::PersistentShell, String> {
Ok(build_local_shell_with_tmpdir(config)?.0)
}
fn build_local_shell_with_tmpdir(
config: &TaskConfig,
) -> Result<(blyte_agent::shell::PersistentShell, Option<PathBuf>), String> {
check_in_place_sandbox(config)?;
if config.sandbox == "on" {
if blyte_agent::sandbox::available() {
let (profile, tmpdir) = build_sandbox_for_root(config, &config.root)?;
if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
eprintln!(
"blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
);
}
if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
eprintln!(
"blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
);
}
if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } = &profile {
eprintln!(
"blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
);
if *block_tcp {
eprintln!(
"blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
);
}
}
let shell =
blyte_agent::shell::PersistentShell::local_sandboxed(config.root.clone(), profile)
.with_tmpdir(tmpdir.clone());
if config.converse {
let root = config.root.clone();
let allow_read = config.allow_read.clone();
let network = config.network == "on";
Ok((
shell.with_profile_builder(Arc::new(move || {
blyte_agent::sandbox::conversation_profile_for_open_edits(
&root,
&allow_read,
network,
)
})),
tmpdir,
))
} else {
Ok((shell, tmpdir))
}
} else {
eprintln!("warning: sandbox unavailable; running unsandboxed");
Ok((
blyte_agent::shell::PersistentShell::local(config.root.clone()),
None,
))
}
} else {
Ok((
blyte_agent::shell::PersistentShell::local(config.root.clone()),
None,
))
}
}
pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
if config.network == "off" {
if config.container.is_some() {
return Err(
"--network=off is not supported with --container; set the container's network instead"
.into(),
);
}
if config.sandbox != "on" {
return Err("--network=off needs the sandbox".into());
}
#[cfg(target_os = "linux")]
if blyte_agent::sandbox::landlock_abi() < 4 {
return Err("--network=off on Linux needs Linux 6.7 or later".into());
}
if !blyte_agent::sandbox::available() {
return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
}
}
Ok(())
}
pub fn write_watchdog_report<F, W: Write>(
config: &TaskConfig,
progress: &Progress,
msg: &str,
elapsed: std::time::Duration,
resolve_model: F,
err_out: &mut W,
) -> Result<Option<crate::report::RunRecord>, String>
where
F: FnOnce(Option<&str>) -> Result<String, String>,
{
let Some(path) = &config.report else {
return Ok(None);
};
let mut record = crate::report::RunRecord::from_error(config, msg, elapsed);
record.turns = progress.turns;
record.gate_attempts = progress.gate_attempts;
record.usage = crate::report::UsageRecord {
input: progress.usage.input,
cached: progress.usage.cached,
output: progress.usage.output,
thinking: progress.usage.thinking,
};
let model_id = match resolve_model(config.model.as_deref()) {
Ok(id) if !id.is_empty() => Some(id),
Ok(_) => {
let _ = writeln!(
err_out,
"blyte: watchdog warning: provider returned empty model id"
);
config.model.clone().filter(|m| !m.is_empty())
}
Err(err) => {
let _ = writeln!(
err_out,
"blyte: watchdog warning: could not resolve provider for cost lookup: {err}"
);
config.model.clone().filter(|m| !m.is_empty())
}
};
if let Some(id) = model_id {
record.cost_usd = blyte_provider::pricing(&id).map(|pr| pr.cost(&progress.usage));
record.model_id = Some(id);
}
crate::report::write(path, &record)?;
Ok(Some(record))
}
pub fn run_task(
config: TaskConfig,
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
let started = std::time::Instant::now();
let progress = Arc::new(Mutex::new(Progress::default()));
if let Some(s) = config.max_seconds {
let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
.ok()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(30);
let watchdog_config = config.clone();
let watchdog_progress = Arc::clone(&progress);
std::thread::spawn(move || {
loop {
let wait_ms = match watchdog_progress.lock() {
Ok(g) => g.gate_wait_ms,
Err(e) => e.into_inner().gate_wait_ms,
};
let deadline = started
+ std::time::Duration::from_secs(s.saturating_add(grace_secs))
+ std::time::Duration::from_millis(wait_ms);
match deadline.checked_duration_since(std::time::Instant::now()) {
Some(remaining) if !remaining.is_zero() => {
std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
}
_ => break,
}
}
let p = match watchdog_progress.lock() {
Ok(g) => *g,
Err(e) => *e.into_inner(),
};
let msg = if p.in_gate {
format!(
"stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
p.gate_attempts
)
} else {
format!(
"stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
p.turns
)
};
let mut stderr = std::io::stderr();
if let Err(err) = write_watchdog_report(
&watchdog_config,
&p,
&msg,
started.elapsed(),
|m| {
blyte_provider::resolve_provider(m)
.map(|pr| pr.model_id())
.map_err(|e| e.to_string())
},
&mut stderr,
) {
eprintln!("blyte: watchdog failed to write report: {err}");
}
eprintln!("blyte: {msg}");
std::process::exit(1);
});
}
let verification_cmd = config.gate.as_deref().unwrap_or("");
let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
state.brief.max_cost_usd = config.max_cost_usd;
let mut stdout = std::io::stdout();
let result =
run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
if let (Err(e), Some(path)) = (&result, &config.report) {
crate::report::write(
path,
&crate::report::RunRecord::from_error(&config, e, started.elapsed()),
)?;
}
result
}
pub fn run_task_with_state_and_writer<W: Write>(
config: &TaskConfig,
state: &mut blyte_agent::state::State,
writer: &mut W,
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
let progress = Arc::new(Mutex::new(Progress::default()));
run_task_with_state_writer_and_progress(config, state, writer, progress)
}
pub fn run_task_with_state_and_events(
config: &TaskConfig,
state: &mut blyte_agent::state::State,
on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
}
pub fn run_task_with_state_and_max_duration(
config: &TaskConfig,
state: &mut blyte_agent::state::State,
max_duration: Option<std::time::Duration>,
on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
}
pub fn run_task_with_approver(
config: &TaskConfig,
state: &mut blyte_agent::state::State,
approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
run_task_with_event_callback(config, state, approver, max_duration, &|event| {
on_event(event)
})
}
pub fn run_task_with_state_writer_and_progress<W: Write>(
config: &TaskConfig,
state: &mut blyte_agent::state::State,
writer: &mut W,
progress: Arc<Mutex<Progress>>,
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
let writer_mutex = Mutex::new(writer);
let on_event = |event: &blyte_agent::run::Event<'_>| {
{
let mut p = match progress.lock() {
Ok(g) => g,
Err(e) => e.into_inner(),
};
match event {
blyte_agent::run::Event::Turn { n, usage, .. } => {
p.turns = *n;
p.usage.input += usage.input;
p.usage.cached += usage.cached;
p.usage.output += usage.output;
p.usage.thinking += usage.thinking;
p.in_gate = false;
}
blyte_agent::run::Event::GateStart { attempt } => {
p.gate_attempts = *attempt;
p.in_gate = true;
}
blyte_agent::run::Event::GateSlotWait { ms } => {
p.gate_wait_ms += ms;
}
blyte_agent::run::Event::Gate { .. } => {
p.in_gate = false;
}
_ => {}
}
}
let line = crate::repl::format_event(event);
if !line.is_empty() {
if let Ok(mut w) = writer_mutex.lock() {
let _ = writeln!(w, "{line}");
}
}
};
let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
run_task_with_event_callback(config, state, None, max_duration, &on_event)
}
fn build_usage_entry(
config: &TaskConfig,
model_id: &str,
outcome: String,
turns: u32,
usage: &blyte_provider::Usage,
) -> crate::usage_log::Entry {
crate::usage_log::Entry {
ts: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
repo: crate::usage_log::repo_of(&config.root),
session: crate::usage_log::session_from(
std::env::var("BLYTE_SESSION").ok(),
std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
),
dispatch: std::env::var("BLYTE_DISPATCH_ID")
.ok()
.filter(|s| !s.is_empty()),
research: config.research,
model: model_id.to_string(),
outcome,
turns,
input: usage.input,
cached: usage.cached,
output: usage.output,
thinking: usage.thinking,
cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
}
}
#[derive(Debug, PartialEq, Eq)]
struct ExceededField {
field: &'static str,
written: u64,
total: u64,
}
fn usage_remainder(
total_turns: u32,
total_usage: &blyte_provider::Usage,
written_turns: u32,
written_usage: &blyte_provider::Usage,
) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
let mut exceeded = Vec::new();
if written_turns > total_turns {
exceeded.push(ExceededField {
field: "turns",
written: u64::from(written_turns),
total: u64::from(total_turns),
});
}
if written_usage.input > total_usage.input {
exceeded.push(ExceededField {
field: "input",
written: written_usage.input,
total: total_usage.input,
});
}
if written_usage.cached > total_usage.cached {
exceeded.push(ExceededField {
field: "cached",
written: written_usage.cached,
total: total_usage.cached,
});
}
if written_usage.output > total_usage.output {
exceeded.push(ExceededField {
field: "output",
written: written_usage.output,
total: total_usage.output,
});
}
if written_usage.thinking > total_usage.thinking {
exceeded.push(ExceededField {
field: "thinking",
written: written_usage.thinking,
total: total_usage.thinking,
});
}
if !exceeded.is_empty() {
return Err(exceeded);
}
Ok((
total_turns - written_turns,
blyte_provider::Usage {
input: total_usage.input - written_usage.input,
cached: total_usage.cached - written_usage.cached,
output: total_usage.output - written_usage.output,
thinking: total_usage.thinking - written_usage.thinking,
},
))
}
fn withheld_notice_is_due(withheld: &[String]) -> bool {
static SHOWN: std::sync::Mutex<Option<Vec<String>>> = std::sync::Mutex::new(None);
if withheld.is_empty() {
return false;
}
let mut shown = SHOWN.lock().unwrap_or_else(|e| e.into_inner());
if shown.as_deref() == Some(withheld) {
return false;
}
*shown = Some(withheld.to_vec());
true
}
fn run_task_with_event_callback(
config: &TaskConfig,
state: &mut blyte_agent::state::State,
approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
max_duration: Option<std::time::Duration>,
on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
check_network_mode(config)?;
check_in_place_sandbox(config)?;
let started = std::time::Instant::now();
let _one_shot_tmp_guard = if config.converse {
if std::env::var("BLYTE_SESSION")
.map(|v| v.is_empty())
.unwrap_or(true)
{
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let id = crate::repl::new_session_id(now_secs, std::process::id());
std::env::set_var("BLYTE_SESSION", &id);
}
let sandbox_on = config.sandbox == "on";
let policy = configure_converse_policy_with_paths(
true,
sandbox_on,
&config.root,
approver,
state.runtime.conversation.is_some(),
)?;
let guard = if state.runtime.conversation.is_none() {
policy.private_tmpdir.map(|p| TempDirGuard(Some(p)))
} else {
None
};
if state.brief.instructions.is_none() {
let lines = crate::conversation_text::set_state_instructions(
state,
config.dispatch_cmd.is_some(),
&config.root,
sandbox_on,
policy.allowed_count,
)?;
if state.runtime.conversation.is_none() {
for line in &lines {
eprintln!("blyte: {line}");
}
}
}
let exe = std::env::current_exe()
.map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
blyte_agent::tools::set_blyte_tool(Some(exe));
if blyte_agent::sandbox::is_git_repository(&config.root) {
blyte_agent::tools::set_blyte_tasks_dir(None);
blyte_agent::tools::set_blyte_run_store(None);
blyte_agent::tools::set_in_place_lock_path(None);
} else {
let state_dir = crate::surface_registry::state_dir()?;
let tasks_dir = crate::surface_dir::tasks_dir(&state_dir, &config.root)?;
let run_store = crate::surface_dir::run_store(&state_dir, &config.root)?;
let lock_path = crate::surface_dir::in_place_lock_path(&state_dir, &config.root)?;
blyte_agent::tools::set_blyte_tasks_dir(Some(tasks_dir));
blyte_agent::tools::set_blyte_run_store(Some(run_store));
blyte_agent::tools::set_in_place_lock_path(Some(lock_path));
}
guard
} else {
configure_converse_policy(false, false, &config.root, None, false)?;
blyte_agent::tools::set_blyte_tool(None);
blyte_agent::tools::set_blyte_tasks_dir(None);
blyte_agent::tools::set_blyte_run_store(None);
blyte_agent::tools::set_in_place_lock_path(None);
None
};
blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
Ok(p) => p,
Err(blyte_provider::ProviderError::MissingKey(key)) => {
return Err(format!(
"Provider error: no API key: set {key} in environment"
));
}
Err(e) => return Err(format!("Provider error: {e}")),
};
let model_id = provider.model_id();
if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
return Err(format!(
"--max-cost needs a known price for {model_id}; none is known"
));
}
state.brief.max_cost_usd = config.max_cost_usd;
let folded = blyte_agent::context::Folded {
budget_tokens: config.fold_budget.unwrap_or(if config.research {
RESEARCH_FOLD_BUDGET
} else {
blyte_agent::context::Folded::default().budget_tokens
}),
};
let conversational = blyte_agent::context::Conversational;
let context_strategy: &dyn blyte_agent::context::ContextStrategy =
match config.context_strategy.as_str() {
"conversational" => &conversational,
_ => &folded,
};
let local_fs = blyte_agent::fs::LocalFs;
let snapshot_fs = match &config.in_place {
Some(in_place) => Some(blyte_agent::snapshot_fs::SnapshotFs::new(
blyte_agent::fs::LocalFs,
config.root.clone(),
in_place.before_dir.clone(),
in_place.manifest.clone(),
)?),
None => None,
};
let mut _in_place_tmp_guard = TempDirGuard(None);
let (persistent, session_fs, root) = match &config.container {
Some(cid) => (
blyte_agent::shell::PersistentShell::container(
cid.clone(),
PathBuf::from(&config.container_workdir),
),
Some(blyte_agent::fs::SessionFs::container(
cid.clone(),
PathBuf::from(&config.container_workdir),
)),
PathBuf::from(&config.container_workdir),
),
None => {
blyte_agent::shell::set_pass_env(config.pass_env.clone());
if !config.converse {
if let Some(r) = blyte_agent::rules::load(&config.root) {
eprintln!("blyte: repository rules from {}", r.source.display());
}
}
let withheld = blyte_agent::shell::withheld_env();
if withheld_notice_is_due(&withheld) {
eprintln!(
"blyte: withholding from commands: {} (keep one with --pass-env NAME)",
withheld.join(", ")
);
}
let (shell, tmpdir) = build_local_shell_with_tmpdir(config)?;
if config.in_place.is_some() {
_in_place_tmp_guard.0 = tmpdir;
}
(shell, None, config.root.clone())
}
};
let shell: &dyn blyte_agent::shell::Shell = &persistent;
let fs: &dyn blyte_agent::fs::Fs = match (&session_fs, &snapshot_fs) {
(Some(f), _) => f,
(None, Some(f)) => f,
(None, None) => &local_fs,
};
let usage_path = crate::usage_log::default_path();
let written = Mutex::new((0u32, blyte_provider::Usage::default()));
let runner_on_event = |event: blyte_agent::run::Event<'_>| {
if let blyte_agent::run::Event::Turn { usage, .. } = &event {
if let Some(path) = &usage_path {
let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
match crate::usage_log::append(path, &entry) {
Ok(()) => {
let mut w = match written.lock() {
Ok(g) => g,
Err(e) => e.into_inner(),
};
w.0 += 1;
w.1.input += usage.input;
w.1.cached += usage.cached;
w.1.output += usage.output;
w.1.thinking += usage.thinking;
}
Err(err) => eprintln!("warning: usage log: {err}"),
}
}
}
on_event(&event);
};
let bg_base_check = match &config.base_check_dir {
Some(base_dir)
if !blyte_agent::run::gate_steps(&state.brief.verification_cmd).is_empty() =>
{
let deadline = max_duration.map(|d| std::time::Instant::now() + d);
Some(BackgroundBaseCheck::start(
config,
state.brief.verification_cmd.clone(),
base_dir.clone(),
deadline,
)?)
}
_ => None,
};
let base_check = if let Some(ref bg) = bg_base_check {
blyte_agent::run::BaseCheck::Polled(bg)
} else if config.base_check {
blyte_agent::run::BaseCheck::BeforeFirstTurn
} else {
blyte_agent::run::BaseCheck::None
};
let runner = blyte_agent::run::Runner {
provider: provider.as_ref(),
shell,
fs,
context: context_strategy,
root,
budget: blyte_agent::run::Budget {
max_turns: config.max_turns as u32,
max_gate_attempts: config.max_gates as u32,
max_duration,
},
rollback: config.rollback && config.in_place.is_none(),
on_event: Some(&runner_on_event),
research: config.research,
claim_check: config.claim_check,
base_check,
};
let (mut outcome, report) = runner.run(state);
if config.in_place.is_some()
&& state.brief.verification_cmd.trim().is_empty()
&& matches!(outcome, blyte_agent::run::Outcome::Verified)
{
outcome = blyte_agent::run::Outcome::Finished;
}
drop(bg_base_check);
if let Some(path) = &usage_path {
let (written_turns, written_usage) = match written.lock() {
Ok(g) => *g,
Err(e) => *e.into_inner(),
};
let (closing_turns, closing_usage) = match usage_remainder(
report.outcome_turns,
&report.usage,
written_turns,
&written_usage,
) {
Ok(rem) => rem,
Err(exceeded) => {
for ExceededField {
field,
written,
total,
} in exceeded
{
eprintln!(
"error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
);
}
(0, blyte_provider::Usage::default())
}
};
let entry = build_usage_entry(
config,
&model_id,
format!("{outcome:?}").to_lowercase(),
closing_turns,
&closing_usage,
);
if let Err(err) = crate::usage_log::append(path, &entry) {
eprintln!("warning: usage log: {err}");
}
}
if let Some(path) = &config.report {
let mut record = crate::report::RunRecord::from_run(
config,
&model_id,
&outcome,
&report,
state,
started.elapsed(),
);
record.effort = provider.effort();
crate::report::write(path, &record)?;
}
Ok((outcome, report))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn usage_remainder_computes_exact_and_partial_remainders() {
let total = blyte_provider::Usage {
input: 600,
cached: 150,
output: 90,
thinking: 75,
};
let exact = usage_remainder(3, &total, 3, &total).unwrap();
assert_eq!(exact, (0, blyte_provider::Usage::default()));
let written = blyte_provider::Usage {
input: 500,
cached: 100,
output: 80,
thinking: 50,
};
let partial = usage_remainder(3, &total, 2, &written).unwrap();
assert_eq!(
partial,
(
1,
blyte_provider::Usage {
input: 100,
cached: 50,
output: 10,
thinking: 25,
}
)
);
}
#[test]
fn usage_remainder_reports_exceeding_fields() {
let total = blyte_provider::Usage {
input: 100,
cached: 20,
output: 30,
thinking: 10,
};
let written = blyte_provider::Usage {
input: 120,
cached: 20,
output: 35,
thinking: 10,
};
let err = usage_remainder(2, &total, 3, &written).unwrap_err();
assert_eq!(
err,
vec![
ExceededField {
field: "turns",
written: 3,
total: 2,
},
ExceededField {
field: "input",
written: 120,
total: 100,
},
ExceededField {
field: "output",
written: 35,
total: 30,
},
]
);
}
fn test_task_config(root: &Path, report: Option<PathBuf>, model: Option<String>) -> TaskConfig {
TaskConfig {
prompt: "test".to_string(),
gate: Some("true".to_string()),
context_strategy: "folded".to_string(),
model,
container: None,
max_turns: 10,
max_gates: 3,
rollback: false,
root: root.to_path_buf(),
container_workdir: "/workspace".to_string(),
max_seconds: Some(10),
max_cost_usd: None,
report,
fold_budget: None,
sandbox: "off".to_string(),
network: "on".to_string(),
allow_read: Vec::new(),
pass_env: Vec::new(),
research: false,
claim_check: false,
base_check: false,
base_check_dir: None,
converse: false,
dispatch_cmd: None,
in_place: None,
}
}
#[test]
fn watchdog_report_write_failure_names_path_and_model_id_is_never_empty() {
let dir = tempfile::tempdir().unwrap();
let report_dir = dir.path().join("unwritable.report.json");
std::fs::create_dir_all(&report_dir).unwrap();
let cfg = test_task_config(dir.path(), Some(report_dir.clone()), None);
let progress = Progress {
turns: 2,
gate_attempts: 1,
in_gate: false,
gate_wait_ms: 0,
usage: blyte_provider::Usage {
input: 1000,
cached: 0,
output: 500,
thinking: 0,
},
};
let mut err_buf = Vec::new();
let err = write_watchdog_report(
&cfg,
&progress,
"stopped past --max-seconds",
std::time::Duration::from_secs(5),
|_| Err("missing API key".to_string()),
&mut err_buf,
)
.expect_err("writing watchdog report to a directory must fail");
assert!(
err.contains(&report_dir.display().to_string()),
"write error must name report path, got: {err}"
);
let warning = String::from_utf8(err_buf).unwrap();
assert!(
warning.contains("missing API key"),
"provider resolution error must be logged, got: {warning}"
);
let ok_report = dir.path().join("ok.report.json");
let ok_cfg = test_task_config(dir.path(), Some(ok_report.clone()), None);
let mut ok_err = Vec::new();
let rec = write_watchdog_report(
&ok_cfg,
&progress,
"stopped past --max-seconds",
std::time::Duration::from_secs(5),
|_| Ok("gemini-3.8-flash-high".to_string()),
&mut ok_err,
)
.expect("writing watchdog report to file must succeed")
.expect("record must be returned");
assert_eq!(rec.model_id.as_deref(), Some("gemini-3.8-flash-high"));
assert!(rec.cost_usd.is_some());
let fallback_report = dir.path().join("fallback.report.json");
let fallback_cfg = test_task_config(dir.path(), Some(fallback_report), None);
let mut fallback_err = Vec::new();
let fallback_rec = write_watchdog_report(
&fallback_cfg,
&progress,
"stopped past --max-seconds",
std::time::Duration::from_secs(5),
|_| Err("no provider".to_string()),
&mut fallback_err,
)
.expect("writing watchdog report must succeed")
.expect("record must be returned");
assert_ne!(fallback_rec.model_id.as_deref(), Some(""));
assert_eq!(fallback_rec.model_id, None);
assert!(String::from_utf8(fallback_err)
.unwrap()
.contains("no provider"));
}
}