use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::Duration;
use blyte_provider::{Message, Provider, ProviderError, Request, StreamTiming, Usage};
use crate::claim_check;
use crate::context::ContextStrategy;
use crate::fs::Fs;
use crate::gate_slots;
use crate::quote_expand;
use crate::research_check;
use crate::shell::Shell;
use crate::state::State;
use crate::tools;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Verified,
Finished,
BudgetExhausted,
GateFailed,
Blocked(String),
Error(String),
}
#[derive(Debug, Clone)]
pub struct Budget {
pub max_turns: u32,
pub max_gate_attempts: u32,
pub max_duration: Option<Duration>,
}
impl Default for Budget {
fn default() -> Self {
Self {
max_turns: 60,
max_gate_attempts: 5,
max_duration: None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TurnUsage {
pub turn: u32,
pub input: u64,
pub cached: u64,
pub output: u64,
pub thinking: u64,
pub prompt_messages: usize,
pub appended: bool,
pub new_chars: usize,
#[serde(default)]
pub fold_budget: Option<usize>,
#[serde(default)]
pub model_ms: u64,
#[serde(default)]
pub tools_ms: u64,
#[serde(default)]
pub first_data_ms: Option<u64>,
#[serde(default)]
pub max_gap_ms: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub failed_attempts: Vec<FailedAttempt>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FailedAttempt {
pub elapsed_ms: u64,
pub timed_out: bool,
pub first_data_ms: Option<u64>,
pub max_gap_ms: u64,
}
fn message_chars(m: &Message) -> usize {
match m {
Message::User(t) | Message::Assistant(t) => t.len(),
Message::ToolCall { arguments, .. } => arguments.to_string().len(),
Message::ToolResult { content, .. } => content.len(),
}
}
#[derive(Debug, Clone, Default)]
pub struct RunReport {
pub outcome_turns: u32,
pub usage: Usage,
pub empty_turns: u32,
pub truncated_turns: u32,
pub read_loop: bool,
pub peak_read_repeats: u32,
pub fold_thrash: bool,
pub stalled: bool,
pub big_read_turns: u32,
pub tool_calls: u32,
pub gate_attempts: u32,
pub provider_retries: u32,
pub turn_usage: Vec<TurnUsage>,
pub gate_ms: Vec<u64>,
pub gate_turns: Vec<u32>,
pub gate_wait_ms: Vec<u64>,
pub gate_failures: Vec<String>,
pub tool_counts: BTreeMap<String, u32>,
pub cost_capped: bool,
pub final_message: Option<String>,
pub quote_problems: Option<Vec<String>>,
pub claim_check: Option<claim_check::ClaimCheck>,
pub claim_check_skipped: Option<String>,
pub base_check_seconds: Option<f64>,
pub base_check_passed: Option<bool>,
}
#[derive(Debug, Clone)]
pub enum Event<'e> {
Turn {
n: u32,
text: &'e str,
usage: Usage,
},
ToolStart {
name: &'e str,
input: String,
},
Tool {
name: &'e str,
input: String,
summary: String,
is_error: bool,
},
Retry {
attempt: u32,
max: u32,
wait_ms: u64,
reason: String,
},
GateStart {
attempt: u32,
},
GateSlotWait {
ms: u64,
},
Gate {
attempt: u32,
passed: bool,
output: &'e str,
},
RolledBack {
to: &'e str,
},
}
pub const MAX_PROVIDER_RETRIES: u32 = 6;
pub const PEER_MESSAGE_PREFIX: &str = "[blyte] Message from surface ";
pub const CONVERSATION_FIXED: &str = "\
Change nothing outside the repository yourself (blyte's own files under `.wt/` and its records are fine).\n\n\
## Working efficiently\n\
Independent reads, searches and commands can be issued as several tool calls in one \
turn: they run in order and you see every result together. Batch them whenever one \
does not depend on another's result; every turn you save is a full model call.\n";
pub const NO_PROGRESS_TURNS: u32 = 20;
pub const NO_PROGRESS_MIN_TURNS: u32 = 8;
pub const NO_PROGRESS_TIME_FRACTION: f64 = 0.25;
pub const LAST_CALL_TURNS: u32 = 10;
pub const LAST_CALL_TIME_FRACTION: f64 = 0.5;
pub const RESEARCH_FIRST_REPORT_TURN: u32 = 8;
pub const READ_LOOP_WARN: u32 = 20;
const READ_LOOP_LIMIT: u32 = 30;
pub const READ_LOOP_GRACE_TURNS: u32 = 3;
pub const CLAIM_CHECK_RESERVE_MAX: Duration = Duration::from_secs(180);
pub fn claim_check_reserve(max_duration: Duration) -> Duration {
(max_duration / 10).min(CLAIM_CHECK_RESERVE_MAX)
}
fn truncated(reason: Option<&str>) -> bool {
matches!(
reason,
Some("MAX_TOKENS" | "CONTINUATION" | "max_tokens" | "length" | "incomplete")
)
}
fn parse_resets_in_seconds(body: &str) -> Option<u64> {
let key = "\"resets_in_seconds\"";
let pos = body.find(key)?;
let rest = body[pos + key.len()..].trim_start();
let after_colon = rest.strip_prefix(':')?.trim_start();
let digits: String = after_colon
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
if digits.is_empty() {
return None;
}
digits.parse().ok()
}
pub fn quota_exhausted(e: &ProviderError) -> Option<String> {
let ProviderError::Api { status: 429, body } = e else {
return None;
};
let resets_in_seconds = parse_resets_in_seconds(body);
let is_quota = body.contains("usage_limit_reached")
|| body.contains("insufficient_quota")
|| body.contains("PerDay")
|| resets_in_seconds.is_some_and(|s| s > 300);
if !is_quota {
return None;
}
let mut msg = "usage quota exhausted; not retrying".to_string();
if let Some(secs) = resets_in_seconds {
let human = if secs >= 86400 {
format!("{}d {}h", secs / 86400, (secs % 86400) / 3600)
} else if secs >= 3600 {
format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
} else {
format!("{}m", secs / 60)
};
msg.push_str(&format!(" (resets in {human})"));
}
Some(msg)
}
pub fn is_transient(e: &ProviderError) -> bool {
if quota_exhausted(e).is_some() {
return false;
}
match e {
ProviderError::Api { status, .. } => matches!(status, 429 | 500 | 502 | 503 | 504),
ProviderError::Transport(_) | ProviderError::NoAnswer { .. } => true,
_ => false,
}
}
fn max_retries_for(e: &ProviderError) -> u32 {
match e {
ProviderError::NoAnswer { .. } => 1,
_ => MAX_PROVIDER_RETRIES,
}
}
pub fn retry_delay(attempt: u32) -> Duration {
if let Ok(ms) = std::env::var("BLYTE_RETRY_DELAY_MS") {
if let Ok(ms) = ms.trim().parse::<u64>() {
return Duration::from_millis(ms);
}
}
let exp = attempt.saturating_sub(1).min(5);
Duration::from_secs((2u64 << exp).min(60))
}
pub fn server_retry_hint(e: &ProviderError) -> Option<Duration> {
let ProviderError::Api { body, .. } = e else {
return None;
};
let key = "\"retryDelay\"";
let rest = &body[body.find(key)? + key.len()..];
let value = &rest[rest.find('"')? + 1..];
let secs: f64 = value[..value.find('s')?].trim().parse().ok()?;
Some(Duration::from_secs_f64(secs.max(0.0)).min(Duration::from_secs(120)))
}
pub fn retry_wait(e: &ProviderError, attempt: u32) -> Duration {
let backoff = retry_delay(attempt);
server_retry_hint(e).map_or(backoff, |hint| hint.max(backoff))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BaseCheckState {
Pending,
Passed,
Failed { steps: Vec<String>, tail: String },
}
pub trait BaseCheckHandle: Sync {
fn poll(&self) -> BaseCheckState;
fn wait(&self) -> BaseCheckState;
fn stop(&self) {}
fn elapsed_seconds(&self) -> Option<f64> {
None
}
}
#[derive(Default)]
pub enum BaseCheck<'a> {
#[default]
None,
BeforeFirstTurn,
Polled(&'a dyn BaseCheckHandle),
}
pub fn base_check_tail(output: &str) -> String {
let lines: Vec<&str> = output.lines().collect();
if lines.len() > 20 {
lines[lines.len() - 20..].join("\n")
} else {
lines.join("\n")
}
}
pub fn base_check_state_from_gate(result: &GateRunResult) -> BaseCheckState {
if result.passed {
BaseCheckState::Passed
} else {
BaseCheckState::Failed {
steps: result.failures.iter().map(|f| f.step.clone()).collect(),
tail: base_check_tail(&result.output),
}
}
}
fn base_check_blocked_message(failing_steps: &[String], tail: &str) -> String {
let steps = failing_steps.join("; ");
format!(
"the check fails before any change ({steps}): {tail}. Fix the environment or the base commit, or pass --no-base-check if this task is meant to fix that check."
)
}
pub struct Runner<'a> {
pub provider: &'a dyn Provider,
pub shell: &'a dyn Shell,
pub fs: &'a dyn Fs,
pub context: &'a dyn ContextStrategy,
pub root: PathBuf,
pub budget: Budget,
pub rollback: bool,
pub on_event: Option<&'a dyn Fn(Event<'_>)>,
pub research: bool,
pub claim_check: bool,
pub base_check: BaseCheck<'a>,
}
const CLAIM_PHRASES: &[&str] = &[
"not caused by",
"pre-existing",
"preexisting",
"already fail",
"unrelated to",
"fails on main",
"fails on the base",
"was failing before",
];
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
impl<'a> Runner<'a> {
fn emit(&self, e: Event<'_>) {
if let Some(f) = self.on_event {
f(e)
}
}
}
impl<'a> Runner<'a> {
fn system_prompt(&self, state: &State, goal: Option<&str>) -> Result<String, String> {
let bins = tools::available_binaries(self.shell, &self.root)?.join(", ");
let where_ = self.shell.describe();
if let Some(text) = &state.brief.instructions {
let request_section = match goal {
Some(goal) => format!("## Your user's first request\n{goal}\n\n"),
None => String::new(),
};
return Ok(format!(
"{text}{request_section}\
## Environment\n{where_}\nAvailable: {bins}\n\n\
{CONVERSATION_FIXED}",
));
}
let rules = crate::rules::prompt_section(&self.root);
let steps = gate_steps(&state.brief.verification_cmd);
let completion = if steps.is_empty() {
"No command checks your work. When you stop, the result is judged by tests you \
cannot see, so verify it yourself first: run the project's existing test suite and \
the tests that cover your change, and check the edge cases the task describes. \
If you searched for problems (with grep or other commands), run those same searches \
again before you stop and confirm they find nothing left to fix. Stop \
only when you are confident the task is complete."
.to_string()
} else {
let verify = steps.join(" && ");
format!(
"Your work is accepted when `{verify}` exits 0. That command is run for you when \
you stop calling tools, and you do not decide the verdict. A failure costs a full \
rerun after your fix, so before you stop, run its quick parts yourself \
(formatting, lint) together with the tests that cover your change; leave the slow \
full run to it. Do not claim to be finished; simply stop when you believe the \
command will pass, and you will be told."
)
};
Ok(format!(
"You are a software engineer working in a repository.\n\n\
## Goal\n{goal}\n\n\
## How completion is decided\n\
{completion}\n\n\
## Environment\n{where_}\nAvailable: {bins}\n\n\
Change nothing outside the repository: no caches, other repositories, \
home-directory files or system settings. If something outside it blocks you \
(disk space, network, a missing tool), say so and stop.\n\n\
{rules}\
## Working efficiently\n\
Independent reads, searches and commands can be issued as several tool calls in one \
turn: they run in order and you see every result together. Batch them whenever one \
does not depend on another's result; every turn you save is a full model call.\n",
goal = goal.unwrap_or(&state.brief.goal),
completion = completion,
where_ = where_,
bins = bins,
rules = rules,
))
}
fn run_gate(
&self,
state: &State,
last_failed: &[String],
deadline: &mut Option<std::time::Instant>,
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> (bool, String, u64, Vec<String>) {
let result = run_gate_steps(
self.shell,
&state.brief.verification_cmd,
&self.root,
last_failed,
deadline,
|ms| self.emit(Event::GateSlotWait { ms }),
now,
);
let failed = result.failures.into_iter().map(|f| f.step).collect();
(result.passed, result.output, result.wait_ms, failed)
}
fn run_step_in(
&self,
cmd: &str,
dir: &Path,
deadline: Option<std::time::Instant>,
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> (bool, String) {
run_gate_step(self.shell, cmd, dir, deadline, now)
}
fn fingerprint(&self) -> Option<String> {
let head = self
.shell
.exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
.ok()?;
if head.exit_code != 0 {
return None;
}
let status = self
.shell
.exec(
"git status --porcelain",
&self.root,
Duration::from_secs(30),
)
.ok()?;
if status.exit_code != 0 {
return None;
}
Some(format!("{}\n{}", head.stdout, status.stdout))
}
fn check_blocked_at_base(&self, base_commit: &str, failing_steps: &[String]) -> bool {
if failing_steps.is_empty() {
return false;
}
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let unique = format!(
"blyte-base-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0),
COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
);
let wt_path = std::env::temp_dir().join(unique);
let add_cmd = format!(
"git worktree add --detach {} {}",
sh_quote(&wt_path.to_string_lossy()),
sh_quote(base_commit)
);
let add_out = match self
.shell
.exec(&add_cmd, &self.root, Duration::from_secs(60))
{
Ok(o) if o.exit_code == 0 => o,
_ => return false,
};
let _ = add_out;
struct Guard<'a> {
shell: &'a dyn Shell,
root: &'a Path,
path: PathBuf,
}
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let cmd = format!(
"git worktree remove --force {}",
sh_quote(&self.path.to_string_lossy())
);
let _ = self.shell.exec(&cmd, self.root, Duration::from_secs(60));
let _ = std::fs::remove_dir_all(&self.path);
}
}
let _guard = Guard {
shell: self.shell,
root: &self.root,
path: wt_path.clone(),
};
let mut all_failed = true;
for step in failing_steps {
let (passed, _) = self.run_step_in(step, &wt_path, None, &std::time::Instant::now);
if passed {
all_failed = false;
}
}
all_failed
}
fn checkpoint(&self) -> Option<String> {
let out = self
.shell
.exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
.ok()?;
(out.exit_code == 0).then(|| out.stdout.trim().to_string())
}
fn check_report_quotes(&self, seen_names: &HashSet<String>) -> Vec<String> {
let Ok(raw) = self.fs.read(&self.root.join("report.md")) else {
return Vec::new();
};
let expand_read = |p: &Path| {
let allowed = tools::resolve_for_read(self.fs, &self.root, &p.to_string_lossy())?;
self.fs.read(&allowed)
};
let (report, mut problems) = quote_expand::expand(&raw, &expand_read);
if report != raw {
if let Err(e) = self.fs.write(&self.root.join("report.md"), &report) {
problems.push(format!(
"report.md: could not write the expanded quotes: {e}"
));
}
}
let read_roots = tools::read_roots();
let mut listing = Vec::new();
for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
if let Ok(o) = self.shell.exec(
"git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
dir,
Duration::from_secs(60),
) {
if o.exit_code == 0 {
listing.extend(o.stdout.lines().map(|l| dir.join(l)));
}
}
}
let read = |p: &Path| self.fs.read(p);
let sources = research_check::Sources {
workspace: &self.root,
read_roots: &read_roots,
listing: &listing,
read: &read,
};
problems.extend(research_check::check(&report, &sources));
problems.extend(research_check::unseen_names(&report, seen_names));
problems.extend(research_check::unseen_paths(&report, &sources, seen_names));
problems
}
fn run_claim_check(
&self,
deadline: Option<std::time::Instant>,
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> Option<claim_check::ClaimCheck> {
if !self.claim_check {
return None;
}
let report = self.fs.read(&self.root.join("report.md")).ok()?;
if report.is_empty() {
return None;
}
let read_roots = tools::read_roots();
let mut listing = Vec::new();
for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
if let Ok(o) = self.shell.exec(
"git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
dir,
Duration::from_secs(60),
) {
if o.exit_code == 0 {
listing.extend(o.stdout.lines().map(|l| dir.join(l)));
}
}
}
let read = |p: &Path| self.fs.read(p);
let claims = research_check::claims(
&report,
&research_check::Sources {
workspace: &self.root,
read_roots: &read_roots,
listing: &listing,
read: &read,
},
);
Some(claim_check::check_claims_with_clock(
self.provider,
&claims,
deadline,
now,
))
}
fn reset_to(&self, commit: &str) -> Result<(), String> {
let out = self
.shell
.exec(
&format!("git reset --hard {commit} && git clean -fd"),
&self.root,
Duration::from_secs(120),
)
.map_err(|e| format!("could not roll back to {commit}: {e}"))?;
if out.exit_code != 0 {
let detail = out.merged();
let detail = detail.trim();
return if detail.is_empty() {
Err(format!(
"could not roll back to {commit}: exit {}",
out.exit_code
))
} else {
Err(format!(
"could not roll back to {commit}: exit {}: {detail}",
out.exit_code
))
};
}
Ok(())
}
fn elapsed_fraction(
&self,
deadline: Option<std::time::Instant>,
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> Option<f64> {
let max_duration = self.budget.max_duration?;
let deadline = deadline?;
let remaining = deadline.saturating_duration_since(now());
Some(max_duration.saturating_sub(remaining).as_secs_f64() / max_duration.as_secs_f64())
}
pub fn run(&self, state: &mut State) -> (Outcome, RunReport) {
self.run_with_clock(state, &std::time::Instant::now)
}
pub fn run_with_clock(
&self,
state: &mut State,
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> (Outcome, RunReport) {
self.run_until(state, now, &std::thread::sleep)
}
pub fn run_with_clock_and_sleep(
&self,
state: &mut State,
now: &(dyn Fn() -> std::time::Instant + Sync),
sleep: &(dyn Fn(std::time::Duration) + Sync),
) -> (Outcome, RunReport) {
self.run_until(state, now, sleep)
}
fn run_until(
&self,
state: &mut State,
now: &(dyn Fn() -> std::time::Instant + Sync),
sleep: &(dyn Fn(std::time::Duration) + Sync),
) -> (Outcome, RunReport) {
if state.runtime.conversation.is_some()
&& state.runtime.conversation_goal.is_none()
&& !state.brief.goal.starts_with(PEER_MESSAGE_PREFIX)
{
state.runtime.conversation_goal = Some(state.brief.goal.clone());
}
let mut history = match &state.runtime.conversation {
None => vec![Message::User(format!("Begin. {}", state.brief.goal))],
Some(prev) if prev.is_empty() => {
vec![Message::User(format!("Begin. {}", state.brief.goal))]
}
Some(prev) => {
let mut h = prev.clone();
h.push(Message::User(state.brief.goal.clone()));
h
}
};
let goal = match &state.runtime.conversation_goal {
Some(g) => Some(g.as_str()),
None if state.brief.goal.starts_with(PEER_MESSAGE_PREFIX) => None,
None => Some(state.brief.goal.as_str()),
};
let system = match self.system_prompt(state, goal) {
Ok(s) => s,
Err(err) => {
if let BaseCheck::Polled(handle) = self.base_check {
handle.stop();
}
if state.runtime.conversation.is_some() {
state.runtime.conversation = Some(history);
}
return (Outcome::Error(err), RunReport::default());
}
};
let mut seen_names = HashSet::new();
if self.research {
if let Some(g) = goal {
seen_names.extend(research_check::identifiers(g).map(str::to_owned));
}
seen_names.extend(research_check::identifiers(&state.brief.goal).map(str::to_owned));
for msg in &history {
if let Message::ToolResult { content, .. } = msg {
seen_names.extend(research_check::identifiers(content).map(str::to_owned));
}
}
}
let baseline = self.checkpoint();
let start_fp = self.fingerprint();
let deadline = self.budget.max_duration.map(|d| now() + d);
let loop_deadline = match (
self.research && self.claim_check,
deadline,
self.budget.max_duration,
) {
(true, Some(d), Some(max_d)) => d.checked_sub(claim_check_reserve(max_d)).or(deadline),
_ => deadline,
};
let (outcome, mut report) = self.run_loop(
state,
&mut history,
&mut seen_names,
&system,
baseline,
start_fp,
loop_deadline,
deadline,
now,
sleep,
);
if let BaseCheck::Polled(handle) = self.base_check {
if outcome != Outcome::Verified && report.base_check_passed.is_none() {
match handle.poll() {
BaseCheckState::Pending => {
handle.stop();
}
BaseCheckState::Passed => {
report.base_check_passed = Some(true);
report.base_check_seconds = handle.elapsed_seconds();
}
BaseCheckState::Failed { .. } => {
report.base_check_passed = Some(false);
report.base_check_seconds = handle.elapsed_seconds();
}
}
}
}
if self.research
&& outcome != Outcome::Verified
&& self
.fs
.read(&self.root.join("report.md"))
.is_ok_and(|s| !s.is_empty())
{
if report.quote_problems.is_none() {
let mut problems = self.check_report_quotes(&seen_names);
problems.truncate(research_check::MAX_PROBLEMS);
report.quote_problems = Some(problems);
}
if report.claim_check.is_none() && report.claim_check_skipped.is_none() {
if let Some(cc) = self.run_claim_check(deadline, now) {
report.usage.input += cc.usage.input;
report.usage.cached += cc.usage.cached;
report.usage.output += cc.usage.output;
report.usage.thinking += cc.usage.thinking;
report.claim_check_skipped = cc.skipped.clone();
if cc.calls > 0 || cc.skipped.is_none() {
report.claim_check = Some(cc);
}
}
}
}
if state.runtime.conversation.is_some() {
state.runtime.conversation = Some(history);
}
(outcome, report)
}
#[allow(clippy::too_many_arguments)]
fn run_loop(
&self,
state: &mut State,
history: &mut Vec<Message>,
seen_names: &mut HashSet<String>,
system: &str,
baseline: Option<String>,
start_fp: Option<String>,
deadline: Option<std::time::Instant>,
claim_deadline: Option<std::time::Instant>,
now: &(dyn Fn() -> std::time::Instant + Sync),
sleep: &(dyn Fn(std::time::Duration) + Sync),
) -> (Outcome, RunReport) {
let mut deadline = deadline;
let mut report = RunReport::default();
let specs = tools::specs();
let mut last_sent: Option<Vec<Message>> = None;
let mut last_failed: Vec<String> = Vec::new();
let mut last_fingerprint: Option<String> = None;
let mut call_counts: HashMap<String, u32> = HashMap::new();
let mut repeats: u32 = 0;
let mut read_warn_sent = false;
let mut read_loop_turn: Option<u32> = None;
let mut change_fp = start_fp.clone();
let mut progressed = false;
let mut nudge_turn: Option<u32> = None;
let mut last_call_sent = false;
let mut last_turn_called_tools = false;
let mut last_report = if self.research {
self.fs.read(&self.root.join("report.md")).ok()
} else {
None
};
let mut claim_round_done = false;
let mut prev_turn_start: Option<usize> = None;
let mut thrash: u32 = 0;
let mut last_big_read_warn: Option<u32> = None;
let mut wrap_up_sent = false;
let mut wrap_up_tools_closed = false;
let mut wrap_up_report: Option<String> = None;
if matches!(self.base_check, BaseCheck::BeforeFirstTurn)
&& !gate_steps(&state.brief.verification_cmd).is_empty()
{
let bc_start = now();
let (passed, output, _wait_ms, failing_steps) =
self.run_gate(state, &[], &mut deadline, now);
report.base_check_seconds =
Some(now().saturating_duration_since(bc_start).as_secs_f64());
report.base_check_passed = Some(passed);
if !passed {
let tail = base_check_tail(&output);
let msg = base_check_blocked_message(&failing_steps, &tail);
report.final_message = Some(msg.clone());
return (Outcome::Blocked(msg), report);
}
}
for turn in 1..=self.budget.max_turns {
if read_loop_turn.is_some_and(|t| turn > t + READ_LOOP_GRACE_TURNS) {
return (Outcome::BudgetExhausted, report);
}
if deadline.is_some_and(|d| now() >= d) {
return (Outcome::BudgetExhausted, report);
}
if let Some(cap) = state.brief.max_cost_usd {
if let Some(price) = blyte_provider::pricing(&self.provider.model_id()) {
if price.cost(&report.usage) >= cap {
report.cost_capped = true;
return (Outcome::BudgetExhausted, report);
}
}
}
if let BaseCheck::Polled(handle) = self.base_check {
if report.base_check_passed.is_none() {
match handle.poll() {
BaseCheckState::Pending => {}
BaseCheckState::Passed => {
report.base_check_passed = Some(true);
report.base_check_seconds = handle.elapsed_seconds();
}
BaseCheckState::Failed { steps, tail } => {
report.base_check_passed = Some(false);
report.base_check_seconds = handle.elapsed_seconds();
let msg = base_check_blocked_message(&steps, &tail);
report.final_message = Some(msg.clone());
return (Outcome::Blocked(msg), report);
}
}
}
}
report.outcome_turns = turn;
let turn_start = history.len();
if !wrap_up_sent {
if self.budget.max_turns >= 20 && turn == self.budget.max_turns - 9 {
wrap_up_sent = true;
history.push(Message::User(format!(
"You have 10 turns left of {}. Wrap up now: make sure your work is saved before you run out: committed, or written to the file the task asks for. Then stop calling tools.",
self.budget.max_turns
)));
} else if let (Some(max_duration), Some(deadline)) =
(self.budget.max_duration, deadline)
{
let time_left = deadline.saturating_duration_since(now());
if time_left.as_secs_f64() < max_duration.as_secs_f64() * 0.1 {
wrap_up_sent = true;
let m = ((time_left.as_secs_f64() / 60.0).ceil() as u64).max(1);
let total = ((max_duration.as_secs_f64() / 60.0).ceil() as u64).max(1);
history.push(Message::User(format!(
"You have about {m} minutes left of {total}. Wrap up now: make sure your work is saved before you run out: committed, or written to the file the task asks for. Then stop calling tools."
)));
}
}
if wrap_up_sent && self.research {
wrap_up_tools_closed = true;
wrap_up_report = self.fs.read(&self.root.join("report.md")).ok();
}
}
if self.research && turn == RESEARCH_FIRST_REPORT_TURN {
let has_report = self
.fs
.read(&self.root.join("report.md"))
.is_ok_and(|s| !s.trim().is_empty());
if !has_report {
history.push(Message::User(
"Start report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
));
}
}
if self.research && turn % 30 == 0 {
let current_report = self.fs.read(&self.root.join("report.md")).ok();
if current_report == last_report {
history.push(Message::User(
"Update report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
));
}
last_report = current_report;
}
if !self.research
&& state.brief.instructions.is_none()
&& state.runtime.conversation.is_none()
&& !progressed
{
let elapsed = self.elapsed_fraction(deadline, now);
if nudge_turn.is_none()
&& (turn > NO_PROGRESS_TURNS
|| (turn > NO_PROGRESS_MIN_TURNS
&& elapsed.is_some_and(|f| f >= NO_PROGRESS_TIME_FRACTION)))
{
if self.fingerprint() != start_fp {
progressed = true;
} else {
let n = turn - 1;
history.push(Message::User(format!(
"[blyte] You have spent {n} turns without changing any file or running the gate. Stop exploring and decide now: make the change the task asks for, or, if the task needs no code change or the problem cannot be reproduced, stop calling tools and explain why in your reply."
)));
nudge_turn = Some(turn);
}
} else if let Some(t) = nudge_turn {
if !last_call_sent
&& (turn >= t + LAST_CALL_TURNS
|| elapsed.is_some_and(|f| f >= LAST_CALL_TIME_FRACTION))
{
if self.fingerprint() != start_fp {
progressed = true;
} else {
history.push(Message::User(
"[blyte] Still no change after the last reminder. Reply now with your conclusion and why, and do not call any tools: the run stops if this reply calls a tool without changing anything."
.to_string(),
));
last_call_sent = true;
}
} else if last_call_sent && last_turn_called_tools {
if self.fingerprint() != start_fp {
progressed = true;
} else {
report.stalled = true;
return (Outcome::BudgetExhausted, report);
}
}
}
}
let fold_budget = self.context.fold_budget(history);
if let Some(prev_start) = prev_turn_start {
if let Some(budget) = fold_budget {
let n: usize = history[prev_start..]
.iter()
.filter(|m| matches!(m, Message::ToolResult { .. }))
.map(crate::context::approx_tokens)
.sum();
if n > budget / 2 {
report.big_read_turns += 1;
if last_big_read_warn.is_none_or(|last| turn >= last + 5) {
last_big_read_warn = Some(turn);
history.push(Message::User(format!(
"[blyte] Your last turn's tool output was about {n} tokens, more than half of what stays in context ({budget}). Read narrower ranges so it is not dropped before you use it."
)));
}
}
}
if self
.context
.folds(history)
.last()
.is_some_and(|&(_, b)| b + 1 > prev_start)
{
thrash += 1;
if thrash >= 5 {
report.fold_thrash = true;
return (Outcome::BudgetExhausted, report);
}
if thrash == 2 {
let budget = fold_budget.unwrap_or_default();
history.push(Message::User(format!(
"[blyte] Your recent tool results are being dropped from your context because each turn reads more than fits (about {budget} tokens stay verbatim). Read narrower ranges (at most 200 lines), one or two files per turn, and act on what you have read before reading more."
)));
}
} else {
thrash = 0;
}
}
prev_turn_start = Some(turn_start);
let mut req = Request {
system: system.to_string(),
messages: self.context.build(state, history),
tools: specs.clone(),
max_output_tokens: None,
timeout: None,
};
let (appended, new_chars) = match &last_sent {
Some(prev)
if req.messages.len() >= prev.len()
&& req.messages[..prev.len()] == prev[..] =>
{
(
true,
req.messages[prev.len()..].iter().map(message_chars).sum(),
)
}
_ => (false, req.messages.iter().map(message_chars).sum()),
};
last_sent = Some(req.messages.clone());
let model_start = now();
let mut attempt = 0;
let mut failed_attempts: Vec<FailedAttempt> = Vec::new();
let resp = loop {
if let Some(d) = deadline {
let time_left = d.saturating_duration_since(now());
if time_left.is_zero() {
return (Outcome::BudgetExhausted, report);
}
req.timeout = Some(time_left);
}
let call_start = std::time::Instant::now();
match self.provider.complete(&req) {
Ok(r) => break r,
Err(e) => {
let (u_in, u_cached, u_out, u_think) = match &e {
ProviderError::NoAnswer { usage, .. } => {
report.usage.input += usage.input;
report.usage.cached += usage.cached;
report.usage.output += usage.output;
report.usage.thinking += usage.thinking;
(usage.input, usage.cached, usage.output, usage.thinking)
}
_ => (0, 0, 0, 0),
};
let push_deadline_turn = |report: &mut RunReport| {
let timing = self.provider.last_stream_timing().unwrap_or_default();
report.turn_usage.push(TurnUsage {
turn,
input: u_in,
cached: u_cached,
output: u_out,
thinking: u_think,
prompt_messages: req.messages.len(),
appended,
new_chars,
fold_budget,
model_ms: now().saturating_duration_since(model_start).as_millis()
as u64,
tools_ms: 0,
first_data_ms: timing.first_data_ms,
max_gap_ms: timing.max_gap_ms,
failed_attempts: failed_attempts.clone(),
});
};
if quota_exhausted(&e).is_none() && deadline.is_some_and(|d| now() >= d) {
push_deadline_turn(&mut report);
return (Outcome::BudgetExhausted, report);
}
let max_retries = max_retries_for(&e);
if is_transient(&e) && attempt < max_retries {
let elapsed = call_start.elapsed().as_secs_f64().round() as u64;
let s = if elapsed > 0 {
elapsed
} else {
blyte_provider::model_timeout_secs()
};
attempt += 1;
let wait = retry_wait(&e, attempt);
if deadline.is_some_and(|d| now() + wait >= d) {
push_deadline_turn(&mut report);
return (Outcome::BudgetExhausted, report);
}
report.provider_retries += 1;
let timing = self.provider.last_stream_timing().unwrap_or_default();
failed_attempts.push(FailedAttempt {
elapsed_ms: call_start.elapsed().as_millis() as u64,
timed_out: e.is_timeout(),
first_data_ms: timing.first_data_ms,
max_gap_ms: timing.max_gap_ms,
});
let reason = if e.is_timeout() {
format!(
"model call timed out after {s} s; retrying ({attempt} of {max_retries}; raise BLYTE_MODEL_IDLE_TIMEOUT_SECS for silence or BLYTE_MODEL_TIMEOUT_SECS for whole call)"
)
} else {
format!(
"provider: {e}; retrying in {}s ({attempt}/{max_retries})",
wait.as_secs()
)
};
eprintln!("{reason}");
self.emit(Event::Retry {
attempt,
max: max_retries,
wait_ms: wait.as_millis() as u64,
reason,
});
sleep(wait);
} else {
let err_msg = match quota_exhausted(&e) {
Some(msg) => format!("{msg}: {e}"),
None => e.to_string(),
};
return (Outcome::Error(err_msg), report);
}
}
}
};
let model_ms = now().saturating_duration_since(model_start).as_millis() as u64;
let timing: StreamTiming = self.provider.last_stream_timing().unwrap_or_default();
report.usage.input += resp.usage.input;
report.usage.cached += resp.usage.cached;
report.usage.output += resp.usage.output;
report.usage.thinking += resp.usage.thinking;
report.turn_usage.push(TurnUsage {
turn,
input: resp.usage.input,
cached: resp.usage.cached,
output: resp.usage.output,
thinking: resp.usage.thinking,
prompt_messages: req.messages.len(),
appended,
new_chars,
fold_budget,
model_ms,
tools_ms: 0,
first_data_ms: timing.first_data_ms,
max_gap_ms: timing.max_gap_ms,
failed_attempts,
});
let trimmed = resp.text.trim();
self.emit(Event::Turn {
n: turn,
text: trimmed,
usage: resp.usage,
});
if truncated(resp.finish_reason.as_deref()) {
last_turn_called_tools = false;
report.truncated_turns += 1;
history.push(Message::User(
"Your last reply hit the output token limit and was cut off, so none of it was used. Reply again more briefly: make one tool call at a time and keep edits small.".to_string(),
));
continue;
}
if trimmed.is_empty() && resp.tool_calls.is_empty() {
report.empty_turns += 1;
}
if !trimmed.is_empty() {
report.final_message = Some(trimmed.to_string());
history.push(Message::Assistant(resp.text.clone()));
}
if !resp.tool_calls.is_empty() {
last_turn_called_tools = true;
let tools_start = now();
for call in &resp.tool_calls {
history.push(Message::ToolCall {
id: call.id.clone(),
name: call.name.clone(),
arguments: call.arguments.clone(),
signature: call.signature.clone(),
});
}
let current_fp = self.fingerprint();
if current_fp != start_fp {
progressed = true;
}
if current_fp != change_fp {
call_counts.clear();
repeats = 0;
read_warn_sent = false;
change_fp = current_fp;
}
for call in &resp.tool_calls {
if deadline.is_some_and(|d| now() >= d) {
report.turn_usage.last_mut().unwrap().tools_ms =
now().saturating_duration_since(tools_start).as_millis() as u64;
return (Outcome::BudgetExhausted, report);
}
report.tool_calls += 1;
*report.tool_counts.entry(call.name.clone()).or_default() += 1;
if wrap_up_tools_closed
&& self
.fs
.read(&self.root.join("report.md"))
.ok()
.is_some_and(|s| {
!s.is_empty() && Some(s.as_str()) != wrap_up_report.as_deref()
})
{
wrap_up_tools_closed = false;
}
let read_closed = read_loop_turn.is_some()
&& matches!(call.name.as_str(), "read" | "grep" | "glob");
let wrap_up_closed =
wrap_up_tools_closed && !matches!(call.name.as_str(), "write" | "edit");
let tool_closed = read_closed || wrap_up_closed;
let input = if call.name == "read" {
extract_action_target(&call.name, &call.arguments)
.chars()
.take(100)
.collect()
} else {
let clean = |s: &str| s.trim_end().replace('\n', " ↵ ");
let text = if call.name == "blyte" {
format_blyte_tool_input(&call.arguments)
.map(|s| clean(&s))
.unwrap_or_else(|| clean(&call.arguments.to_string()))
} else {
call.arguments
.get("command")
.or_else(|| call.arguments.get("pattern"))
.or_else(|| call.arguments.get("path"))
.and_then(|v| v.as_str())
.map(clean)
.unwrap_or_else(|| clean(&call.arguments.to_string()))
};
if text.chars().count() > 2000 {
let mut cut: String = text.chars().take(2000).collect();
cut.push('…');
cut
} else {
text
}
};
self.emit(Event::ToolStart {
name: &call.name,
input: input.clone(),
});
let mut outcome = if read_closed {
tools::ToolOutcome {
content: "[blyte] reading is closed; write report.md now from what you have found.".to_string(),
is_error: true,
}
} else if wrap_up_closed {
tools::ToolOutcome {
content: "[blyte] almost out of budget: write report.md now (write or edit). Other tools are closed until report.md has changed.".to_string(),
is_error: true,
}
} else {
let tool_timeout = deadline
.map(|d| d.saturating_duration_since(now()))
.unwrap_or(Duration::MAX);
tools::execute_with_timeout(
&self.root,
self.shell,
self.fs,
&call.name,
&call.arguments,
tool_timeout,
)
};
let summary = outcome
.content
.lines()
.next()
.unwrap_or("")
.chars()
.take(90)
.collect::<String>();
self.emit(Event::Tool {
name: &call.name,
input,
summary,
is_error: outcome.is_error,
});
if self.research && !tool_closed {
seen_names.extend(
research_check::identifiers(&outcome.content).map(str::to_owned),
);
}
if !outcome.is_error && matches!(call.name.as_str(), "edit" | "write") {
progressed = true;
call_counts.clear();
repeats = 0;
read_warn_sent = false;
} else if !tool_closed && matches!(call.name.as_str(), "read" | "grep" | "glob")
{
let key = format!("{}:{}", call.name, call.arguments);
let n = call_counts.entry(key).or_insert(0);
*n += 1;
let n = *n;
if n >= 2 {
repeats += 1;
report.peak_read_repeats = report.peak_read_repeats.max(repeats);
}
if n >= 3 {
let tail = if self.research {
"write what you need into report.md"
} else {
"and make your change"
};
outcome.content.push_str(&format!(
"\n\n[blyte] You have made this exact call {n} times since the workspace last changed; earlier results were dropped from your context to save space. Do not read it again: note what you need from it in your reply, read only the lines you need, {tail}."
));
}
if self.research && !read_warn_sent && repeats >= READ_LOOP_WARN {
read_warn_sent = true;
outcome.content.push_str(&format!(
"\n\n[blyte] You have re-read {READ_LOOP_WARN} files or searches since the workspace last changed; earlier results were dropped to save space. Write what you need into report.md now; reading stops at {READ_LOOP_LIMIT}."
));
}
}
history.push(Message::ToolResult {
id: call.id.clone(),
name: call.name.clone(),
content: outcome.content,
is_error: outcome.is_error,
});
if repeats >= READ_LOOP_LIMIT && read_loop_turn.is_none() {
report.read_loop = true;
if !self.research {
report.turn_usage.last_mut().unwrap().tools_ms =
now().saturating_duration_since(tools_start).as_millis() as u64;
return (Outcome::BudgetExhausted, report);
}
read_loop_turn = Some(turn);
}
}
if read_loop_turn == Some(turn) {
history.push(Message::User(
"[blyte] Stop reading; write report.md now from what you have found, mark what you could not confirm as open questions, then stop calling tools.".to_string(),
));
}
report.turn_usage.last_mut().unwrap().tools_ms =
now().saturating_duration_since(tools_start).as_millis() as u64;
continue;
}
last_turn_called_tools = false;
if report.gate_attempts > 0
&& CLAIM_PHRASES
.iter()
.any(|&p| resp.text.to_lowercase().contains(p))
{
if let (Some(last_fp), Some(curr_fp), Some(base_commit)) =
(&last_fingerprint, self.fingerprint(), &baseline)
{
if *last_fp == curr_fp && self.check_blocked_at_base(base_commit, &last_failed)
{
let steps = last_failed.join("; ");
let text: String = resp.text.chars().take(300).collect();
return (
Outcome::Blocked(format!(
"the check fails at the base commit too ({steps}); the model said: {text}"
)),
report,
);
}
}
}
if state.brief.verification_cmd.trim().is_empty() {
if state.brief.instructions.is_some() {
return (Outcome::Finished, report);
}
self.finalize_polled_base_check(&mut report);
return (Outcome::Verified, report);
}
progressed = true;
report.gate_attempts += 1;
report.gate_turns.push(turn);
self.emit(Event::GateStart {
attempt: report.gate_attempts,
});
let gate_start = now();
let (mut passed, mut output, wait_ms, failing) =
self.run_gate(state, &last_failed, &mut deadline, now);
last_failed = failing;
if passed && self.research {
let mut problems = self.check_report_quotes(seen_names);
if !problems.is_empty() {
passed = false;
output = format!("exit 1\n{}", research_check::render(&problems));
}
problems.truncate(research_check::MAX_PROBLEMS);
report.quote_problems = Some(problems);
if passed {
if let Some(cc) = self.run_claim_check(claim_deadline, now) {
report.usage.input += cc.usage.input;
report.usage.cached += cc.usage.cached;
report.usage.output += cc.usage.output;
report.usage.thinking += cc.usage.thinking;
report.claim_check_skipped = cc.skipped.clone();
if !cc.contradicted.is_empty() && !claim_round_done {
claim_round_done = true;
passed = false;
let mut lines: Vec<String> = cc
.contradicted
.iter()
.map(|f| {
let text: String = f.text.chars().take(200).collect();
format!("report.md:{}: {text}\n checker: {}", f.line, f.reason)
})
.collect();
lines.push(
"These claims do not match the lines they cite. Fix each claim, cite the lines that support it, or remove it."
.to_string(),
);
output = format!("exit 1\n{}", lines.join("\n"));
}
if cc.calls > 0 || cc.skipped.is_none() {
report.claim_check = Some(cc);
}
}
}
}
report
.gate_ms
.push(now().saturating_duration_since(gate_start).as_millis() as u64);
report.gate_wait_ms.push(wait_ms);
self.emit(Event::Gate {
attempt: report.gate_attempts,
passed,
output: output.lines().next().unwrap_or(""),
});
if passed {
self.finalize_polled_base_check(&mut report);
return (Outcome::Verified, report);
}
report.gate_failures.push(cut_gate_output(&output));
if deadline.is_some_and(|d| now() >= d) {
return (Outcome::BudgetExhausted, report);
}
last_fingerprint = self.fingerprint();
if last_fingerprint != start_fp {
progressed = true;
}
if self.rollback {
if let Some(base) = &baseline {
if let Err(msg) = self.reset_to(base) {
return (Outcome::Error(msg), report);
}
state.runtime.rollbacks += 1;
let short_sha = &base[..base.len().min(8)];
self.emit(Event::RolledBack { to: short_sha });
}
}
if report.gate_attempts >= self.budget.max_gate_attempts {
return (Outcome::GateFailed, report);
}
let reset_note = if self.rollback && baseline.is_some() {
"\n\nYour changes have been reverted to the last verified state. Start from \
the current files, not from what you remember writing."
} else {
""
};
let advice = if self.research {
"Fix report.md as listed above, then reply with one line."
} else {
"If the failure is caused by your change, fix your change, not the machine. \
If it is not caused by your change (disk space, network, a missing service), \
say so and stop."
};
history.push(Message::User(format!(
"Verification did not pass.\n\n{output}\n\n{advice}{reset_note}"
)));
}
(Outcome::BudgetExhausted, report)
}
fn finalize_polled_base_check(&self, report: &mut RunReport) {
let BaseCheck::Polled(handle) = self.base_check else {
return;
};
if report.base_check_passed == Some(true) {
if report.base_check_seconds.is_none() {
report.base_check_seconds = handle.elapsed_seconds();
}
return;
}
let final_state = match handle.poll() {
BaseCheckState::Pending => handle.wait(),
other => other,
};
report.base_check_seconds = handle.elapsed_seconds();
match final_state {
BaseCheckState::Passed => {
report.base_check_passed = Some(true);
}
BaseCheckState::Failed { .. } => {
report.base_check_passed = Some(false);
let note = "the check failed on the untouched code but passes with this change";
report.final_message = Some(match report.final_message.take() {
Some(existing) if !existing.is_empty() => format!("{existing}\n\n{note}"),
_ => note.to_string(),
});
}
BaseCheckState::Pending => {}
}
}
}
const SANDBOX_DENIAL_HINT: &str = "hint: \"Operation not permitted\" usually means blyte's sandbox denied a path outside the worktree (for example a .env in the main checkout). Make the check independent of files outside the worktree.";
pub fn sandbox_denial_hint(output: &str) -> Option<&'static str> {
if output
.to_ascii_lowercase()
.contains("operation not permitted")
{
Some(SANDBOX_DENIAL_HINT)
} else {
None
}
}
fn append_hint_line(output: &mut String, hint: &str) {
if output.trim_end_matches(['\r', '\n']).ends_with(hint) {
return;
}
if !output.ends_with('\n') {
output.push('\n');
}
output.push_str(hint);
}
pub fn append_sandbox_denial_hint(output: &mut String) {
if let Some(hint) = sandbox_denial_hint(output) {
append_hint_line(output, hint);
}
}
fn attach_sandbox_denial_hint(result: &mut GateRunResult) {
if result.passed {
return;
}
let hint = sandbox_denial_hint(&result.output).or_else(|| {
result
.failures
.iter()
.find_map(|f| sandbox_denial_hint(&f.output))
});
let Some(hint) = hint else {
return;
};
append_hint_line(&mut result.output, hint);
if let Some(last) = result.failures.last_mut() {
append_hint_line(&mut last.output, hint);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GateStepFailure {
pub step: String,
pub output: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GateRunResult {
pub passed: bool,
pub output: String,
pub wait_ms: u64,
pub failures: Vec<GateStepFailure>,
}
pub fn run_gate_step(
shell: &dyn Shell,
cmd: &str,
dir: &Path,
deadline: Option<std::time::Instant>,
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> (bool, String) {
let timeout = match deadline {
Some(d) => {
let left = d.saturating_duration_since(now());
if left.is_zero() {
return (false, "exit 124\ngate ran out of time".into());
}
Duration::from_secs(1800).min(left)
}
None => Duration::from_secs(1800),
};
let wrapped = format!("(export {}=1\n{cmd}\n)", gate_slots::IN_GATE_ENV);
match shell.exec(&wrapped, dir, timeout) {
Ok(o) => {
let merged = o.merged();
let raw = merged.trim_end();
let body = tools::bound_output(raw);
let dropped: Vec<&str> = if o.exit_code != 0 {
let kept: std::collections::HashSet<&str> = body.lines().map(str::trim).collect();
summary_lines(raw)
.into_iter()
.filter(|l| !kept.contains(l))
.collect()
} else {
Vec::new()
};
let content = if dropped.is_empty() {
body
} else {
let block = format!("Failing, in lines blyte left out:\n{}", dropped.join("\n"));
if body.is_empty() {
block
} else {
format!("{block}\n\n{body}")
}
};
if o.exit_code != 0 && deadline.is_some_and(|d| now() >= d) {
if content.is_empty() {
return (false, format!("exit {}\ngate ran out of time", o.exit_code));
}
return (
false,
format!("exit {}\ngate ran out of time\n{content}", o.exit_code),
);
}
(o.exit_code == 0, format!("exit {}\n{content}", o.exit_code))
}
Err(e) => {
if deadline.is_some_and(|d| now() >= d) {
return (false, format!("gate ran out of time: {e}"));
}
(false, format!("verification command could not run: {e}"))
}
}
}
pub fn run_gate_steps(
shell: &dyn Shell,
gate: &str,
dir: &Path,
last_failed: &[String],
deadline: &mut Option<std::time::Instant>,
on_slot_wait: impl FnOnce(u64),
now: &(dyn Fn() -> std::time::Instant + Sync),
) -> GateRunResult {
run_gate_steps_cancellable(
shell,
gate,
dir,
last_failed,
deadline,
on_slot_wait,
now,
None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn run_gate_steps_cancellable(
shell: &dyn Shell,
gate: &str,
dir: &Path,
last_failed: &[String],
deadline: &mut Option<std::time::Instant>,
on_slot_wait: impl FnOnce(u64),
now: &(dyn Fn() -> std::time::Instant + Sync),
cancel: Option<&crate::shell::CancelHandle>,
) -> GateRunResult {
let (_guard, wait_ms) = if gate_slots::enabled() && !gate_slots::nested() {
let max_slots = gate_slots::slots();
let slot_dir = gate_slots::slot_dir();
match gate_slots::acquire_cancellable(
max_slots,
&slot_dir,
Duration::from_millis(500),
cancel.map(crate::shell::CancelHandle::flag),
) {
Ok(Some((guard, waited))) => {
let wait_ms = waited.as_millis() as u64;
if let Some(d) = deadline.as_mut() {
*d += waited;
}
if wait_ms > 0 {
eprintln!(
"gate: waited {}s for a gate slot ({max_slots} in use)",
waited.as_secs()
);
on_slot_wait(wait_ms);
}
(Some(guard), wait_ms)
}
Ok(None) => {
return GateRunResult {
passed: false,
output: "cancelled".into(),
wait_ms: 0,
failures: Vec::new(),
};
}
Err(e) => {
eprintln!("gate: slot acquisition failed: {e}");
(None, 0)
}
}
} else {
(None, 0)
};
if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
return GateRunResult {
passed: false,
output: "cancelled".into(),
wait_ms,
failures: Vec::new(),
};
}
let steps = gate_steps(gate);
if steps.len() <= 1 {
let step_cmd = steps.first().copied().unwrap_or(gate);
let (passed, output) = run_gate_step(shell, step_cmd, dir, *deadline, now);
let failures = if passed {
Vec::new()
} else {
vec![GateStepFailure {
step: step_cmd.to_string(),
output: output.clone(),
}]
};
let mut result = GateRunResult {
passed,
output,
wait_ms,
failures,
};
attach_sandbox_denial_hint(&mut result);
return result;
}
let (first_group, second_group) = {
let (f, s) = retry_order(&steps, last_failed);
if f.is_empty() {
(steps.clone(), Vec::new())
} else {
(f, s)
}
};
let mut formatted_failures = Vec::new();
let mut failures = Vec::new();
for &step in &first_group {
if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
break;
}
let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
if !passed {
formatted_failures.push(format!("$ {step}\n{output}"));
failures.push(GateStepFailure {
step: step.to_string(),
output,
});
if deadline.is_some_and(|d| now() >= d)
|| cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
{
break;
}
}
}
if !failures.is_empty() {
let body = tools::bound_output(&formatted_failures.join("\n\n"));
let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
let not_rerun = if !second_group.is_empty() {
format!(
"\nNot re-run this attempt: {} step(s) that passed last time ({}).",
second_group.len(),
second_group.join(", ")
)
} else {
String::new()
};
let mut result = GateRunResult {
passed: false,
output: format!(
"{} of {} steps failed: {}{not_rerun}\n\n{body}",
failures.len(),
steps.len(),
failed_names.join(", ")
),
wait_ms,
failures,
};
attach_sandbox_denial_hint(&mut result);
return result;
}
for &step in &second_group {
if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
break;
}
let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
if !passed {
formatted_failures.push(format!("$ {step}\n{output}"));
failures.push(GateStepFailure {
step: step.to_string(),
output,
});
if deadline.is_some_and(|d| now() >= d)
|| cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
{
break;
}
}
}
if failures.is_empty() {
return GateRunResult {
passed: true,
output: "exit 0".into(),
wait_ms,
failures: Vec::new(),
};
}
let body = tools::bound_output(&formatted_failures.join("\n\n"));
let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
let mut result = GateRunResult {
passed: false,
output: format!(
"{} of {} steps failed: {}\n\n{body}",
failures.len(),
steps.len(),
failed_names.join(", ")
),
wait_ms,
failures,
};
attach_sandbox_denial_hint(&mut result);
result
}
pub fn gate_steps(gate: &str) -> Vec<&str> {
gate.lines()
.map(str::trim)
.filter(|s| !s.is_empty())
.collect()
}
pub fn retry_order<'a>(steps: &[&'a str], last_failed: &[String]) -> (Vec<&'a str>, Vec<&'a str>) {
if last_failed.is_empty() {
return (steps.to_vec(), Vec::new());
}
let mut failed = Vec::new();
let mut others = Vec::new();
for &step in steps {
if last_failed.iter().any(|f| f == step) {
failed.push(step);
} else {
others.push(step);
}
}
(failed, others)
}
fn is_summary_line(line: &str) -> bool {
let t = line.trim();
((t.starts_with("FAILED ") || t.starts_with("ERROR "))
&& (t.contains("::") || t.contains(".py")))
|| (t.starts_with('=') && (t.contains(" failed") || t.contains(" error")))
|| (t.starts_with("test ") && t.ends_with("FAILED"))
|| t.starts_with("error[")
|| t.starts_with("error:")
|| t.starts_with("test result: FAILED")
}
fn summary_lines(output: &str) -> Vec<&str> {
let mut lines = Vec::new();
let mut seen = std::collections::HashSet::new();
for line in output.lines() {
let t = line.trim();
if is_summary_line(t) && seen.insert(t) {
lines.push(t);
if lines.len() == 40 {
break;
}
}
}
lines
}
fn is_blyte_header(line: &str) -> bool {
let t = line.trim();
let Some((n, rest)) = t.split_once(" of ") else {
return false;
};
if !n.chars().all(|c| c.is_ascii_digit()) || n.is_empty() {
return false;
}
let Some((m, _)) = rest.split_once(" steps failed:") else {
return false;
};
m.chars().all(|c| c.is_ascii_digit()) && !m.is_empty()
}
pub fn cut_gate_output(output: &str) -> String {
const MAX_CHARS: usize = 4_000;
let total_chars = output.chars().count();
if total_chars <= MAX_CHARS {
return output.to_string();
}
let sum_lines = summary_lines(output);
let has_summary = !sum_lines.is_empty();
let first_line = output.lines().next().unwrap_or("");
let has_blyte_header = is_blyte_header(first_line);
let (header, rem) = if has_summary && has_blyte_header {
let rem = &output[first_line.len()..];
let rem = rem.trim_start_matches(['\r', '\n']);
(Some(first_line), rem)
} else {
(None, output)
};
let summary_block = if has_summary {
let mut block = String::from("Failing, from the full output:\n");
block.push_str(&sum_lines.join("\n"));
Some(block)
} else {
None
};
let prefix_chars = header.map(|h| h.chars().count() + 1).unwrap_or(0)
+ summary_block
.as_ref()
.map(|s| s.chars().count() + 1)
.unwrap_or(0);
let available = MAX_CHARS.saturating_sub(prefix_chars);
let head_budget = available / 4;
let tail_budget = available - head_budget;
let head = if head_budget == 0 || rem.is_empty() {
""
} else {
let head_cand_end = rem
.char_indices()
.nth(head_budget)
.map(|(i, _)| i)
.unwrap_or(rem.len());
let head_cand = &rem[..head_cand_end];
match head_cand.rfind('\n') {
Some(idx) => &head_cand[..idx],
None => head_cand,
}
};
let tail = if tail_budget == 0 {
""
} else {
let tail_cand_start = output
.char_indices()
.nth(total_chars.saturating_sub(tail_budget))
.map(|(i, _)| i)
.unwrap_or(output.len());
let tail_cand = &output[tail_cand_start..];
match tail_cand.find('\n') {
Some(idx) => &tail_cand[idx + 1..],
None => tail_cand,
}
};
let dropped = total_chars.saturating_sub(head.chars().count() + tail.chars().count());
let mut pieces = Vec::new();
if let Some(h) = header {
pieces.push(h);
}
if let Some(sb) = &summary_block {
pieces.push(sb.as_str());
}
if !head.is_empty() {
pieces.push(head);
}
let marker = format!("… [{dropped} characters cut] …");
pieces.push(&marker);
if !tail.is_empty() {
pieces.push(tail);
}
let mut joined = pieces.join("\n");
if output
.trim_end_matches(['\r', '\n'])
.ends_with(SANDBOX_DENIAL_HINT)
{
append_hint_line(&mut joined, SANDBOX_DENIAL_HINT);
}
joined
}
fn format_blyte_arg(arg: &str) -> String {
if arg.is_empty()
|| arg
.chars()
.any(|c| c.is_whitespace() || c == '"' || c == '\'')
{
serde_json::to_string(arg).unwrap_or_else(|_| format!("\"{arg}\""))
} else {
arg.to_string()
}
}
pub fn format_blyte_tool_input(args: &serde_json::Value) -> Option<String> {
let raw_args = args.get("args")?.as_array()?;
let mut parts = Vec::with_capacity(raw_args.len() + 1);
parts.push("blyte".to_string());
for item in raw_args {
parts.push(format_blyte_arg(item.as_str()?));
}
let mut cmd = parts.join(" ");
if args.get("background").and_then(|v| v.as_bool()) == Some(true) {
cmd.push_str(" (background)");
}
Some(cmd)
}
pub fn extract_action_target(tool: &str, args: &serde_json::Value) -> String {
match tool {
"read" => {
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
let start = args.get("start_line").and_then(|v| {
v.as_u64()
.map(|n| n.to_string())
.or_else(|| v.as_str().map(|s| s.to_string()))
});
let end = args.get("end_line").and_then(|v| {
v.as_u64()
.map(|n| n.to_string())
.or_else(|| v.as_str().map(|s| s.to_string()))
});
match (start, end) {
(Some(s), Some(e)) => return format!("{path} (L{s}-L{e})"),
(Some(s), None) => return format!("{path} (L{s}+)"),
(None, Some(e)) => return format!("{path} (L1-L{e})"),
(None, None) => return path.to_string(),
}
}
}
"write" => {
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
return format!("{path} ({} bytes)", content.len());
}
return path.to_string();
}
}
"edit" => {
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
return path.to_string();
}
}
"bash" => {
if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
let single_line = cmd.replace('\n', " ");
if single_line.chars().count() > 60 {
let prefix: String = single_line.chars().take(57).collect();
return format!("{prefix}...");
}
return single_line;
}
}
"glob" => {
if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
return pattern.to_string();
}
}
"grep" => {
if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
if !path.is_empty() {
return format!("pattern '{pattern}' in {path}");
}
}
return format!("pattern '{pattern}'");
}
}
"blyte" => {
if let Some(cmd) = format_blyte_tool_input(args) {
return cmd;
}
}
_ => {}
}
if let Some(obj) = args.as_object() {
for val in obj.values() {
if let Some(s) = val.as_str() {
return s.to_string();
}
}
}
tool.to_string()
}
pub fn extract_action_summary(tool: &str, content: &str, is_error: bool) -> String {
match tool {
"read" => {
if is_error {
let first = content
.lines()
.find(|l| !l.trim().is_empty())
.unwrap_or("read failed");
let clamped: String = first.chars().take(80).collect();
format!("failed: {clamped}")
} else {
let count = content.lines().count();
format!("{count} lines read")
}
}
"write" => {
if is_error {
let first = content
.lines()
.find(|l| !l.trim().is_empty())
.unwrap_or("write failed");
let clamped: String = first.chars().take(80).collect();
format!("failed: {clamped}")
} else {
"file written".to_string()
}
}
"edit" => {
if is_error {
let first = content
.lines()
.find(|l| !l.trim().is_empty())
.unwrap_or("edit failed");
let clamped: String = first.chars().take(80).collect();
format!("failed: {clamped}")
} else {
"string replaced".to_string()
}
}
"bash" => {
if !is_error {
"exit 0".to_string()
} else {
let last_line = content
.lines()
.rev()
.find(|l| !l.trim().is_empty())
.unwrap_or("command failed");
let clamped: String = last_line.chars().take(80).collect();
format!("failed: {clamped}")
}
}
"glob" => {
if is_error {
let first = content
.lines()
.find(|l| !l.trim().is_empty())
.unwrap_or("glob failed");
let clamped: String = first.chars().take(80).collect();
format!("failed: {clamped}")
} else {
let count = content.lines().filter(|l| !l.trim().is_empty()).count();
format!("{count} files matched")
}
}
"grep" => {
if is_error {
let first = content
.lines()
.find(|l| !l.trim().is_empty())
.unwrap_or("grep failed");
let clamped: String = first.chars().take(80).collect();
format!("failed: {clamped}")
} else {
let count = content.lines().filter(|l| !l.trim().is_empty()).count();
format!("{count} matches found")
}
}
_ => {
let first = content.lines().next().unwrap_or("");
first.chars().take(80).collect()
}
}
}