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>,
}
#[derive(Debug, Clone)]
pub enum Event<'e> {
Turn {
n: u32,
text: &'e str,
usage: Usage,
},
Tool {
name: &'e str,
input: String,
summary: String,
is_error: bool,
},
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 ORCHESTRATOR_EXPLORE_NUDGE: u32 = 8;
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;
fn is_dispatch_call(call: &blyte_provider::ToolCall) -> bool {
call.name == "dispatch"
|| (call.name == "bash"
&& call
.arguments
.get("command")
.and_then(|v| v.as_str())
.is_some_and(|cmd| cmd.contains("blyte dispatch")))
}
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))
}
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,
}
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: &str) -> String {
let bins = tools::available_binaries(self.shell, &self.root).join(", ");
let where_ = self.shell.describe();
let rules = crate::rules::prompt_section(&self.root);
if let Some(text) = &state.orchestrator.instructions {
return format!(
"{text}## Your user's first request\n{goal}\n\n\
## Environment\n{where_}\nAvailable: {bins}\n\n\
Change nothing outside the repository yourself (blyte's own files under `.wt/` and its records are fine).\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",
text = text,
goal = goal,
where_ = where_,
bins = bins,
rules = rules,
);
}
let steps = gate_steps(&state.orchestrator.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."
)
};
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,
completion = completion,
where_ = where_,
bins = bins,
rules = rules,
)
}
fn run_gate(
&self,
state: &State,
last_failed: &[String],
deadline: &mut Option<std::time::Instant>,
) -> (bool, String, u64, Vec<String>) {
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(max_slots, &slot_dir, Duration::from_millis(500)) {
Ok((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()
);
self.emit(Event::GateSlotWait { ms: wait_ms });
}
(Some(guard), wait_ms)
}
Err(e) => {
eprintln!("gate: slot acquisition failed: {e}");
(None, 0)
}
}
} else {
(None, 0)
};
let steps = gate_steps(&state.orchestrator.verification_cmd);
if steps.len() <= 1 {
let (passed, output) = self.run_step(&state.orchestrator.verification_cmd, *deadline);
let failed = if passed {
Vec::new()
} else {
vec![state.orchestrator.verification_cmd.clone()]
};
return (passed, output, wait_ms, failed);
}
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 failures = Vec::new();
let mut failed_steps = Vec::new();
for &step in &first_group {
let (passed, output) = self.run_step(step, *deadline);
if !passed {
failed_steps.push(step.to_string());
failures.push(format!("$ {step}\n{output}"));
if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
break;
}
}
}
if !failures.is_empty() {
let body = tools::bound_output(&failures.join("\n\n"));
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()
};
return (
false,
format!(
"{} of {} steps failed: {}{not_rerun}\n\n{body}",
failures.len(),
steps.len(),
failed_steps.join(", ")
),
wait_ms,
failed_steps,
);
}
for &step in &second_group {
let (passed, output) = self.run_step(step, *deadline);
if !passed {
failed_steps.push(step.to_string());
failures.push(format!("$ {step}\n{output}"));
if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
break;
}
}
}
if failures.is_empty() {
return (true, "exit 0".into(), wait_ms, Vec::new());
}
let body = tools::bound_output(&failures.join("\n\n"));
(
false,
format!(
"{} of {} steps failed: {}\n\n{body}",
failures.len(),
steps.len(),
failed_steps.join(", ")
),
wait_ms,
failed_steps,
)
}
fn run_step(&self, cmd: &str, deadline: Option<std::time::Instant>) -> (bool, String) {
self.run_step_in(cmd, &self.root, deadline)
}
fn run_step_in(
&self,
cmd: &str,
dir: &Path,
deadline: Option<std::time::Instant>,
) -> (bool, String) {
let timeout = match deadline {
Some(d) => {
let left = d.saturating_duration_since(std::time::Instant::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 self.shell.exec(&wrapped, dir, timeout) {
Ok(o) => {
let body = tools::bound_output(o.merged().trim_end());
if o.exit_code != 0 && deadline.is_some_and(|d| std::time::Instant::now() >= d) {
if body.is_empty() {
return (false, format!("exit {}\ngate ran out of time", o.exit_code));
}
return (
false,
format!("exit {}\ngate ran out of time\n{body}", o.exit_code),
);
}
(o.exit_code == 0, format!("exit {}\n{body}", o.exit_code))
}
Err(e) => {
if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
return (false, format!("gate ran out of time: {e}"));
}
(false, format!("verification command could not run: {e}"))
}
}
}
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);
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>,
) -> 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(self.provider, &claims, deadline))
}
fn reset_to(&self, commit: &str) {
let _ = self.shell.exec(
&format!("git reset --hard {commit} && git clean -fd"),
&self.root,
Duration::from_secs(120),
);
}
fn elapsed_fraction(&self, deadline: Option<std::time::Instant>) -> Option<f64> {
let max_duration = self.budget.max_duration?;
let deadline = deadline?;
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
Some(max_duration.saturating_sub(remaining).as_secs_f64() / max_duration.as_secs_f64())
}
pub fn run(&self, state: &mut State) -> (Outcome, RunReport) {
let deadline = self
.budget
.max_duration
.map(|d| std::time::Instant::now() + d);
self.run_until(state, deadline)
}
fn run_until(
&self,
state: &mut State,
deadline: Option<std::time::Instant>,
) -> (Outcome, RunReport) {
let is_empty_conversation = state
.runtime
.conversation
.as_ref()
.map(|c| c.is_empty())
.unwrap_or(false);
if is_empty_conversation {
state.runtime.conversation_goal = Some(state.orchestrator.goal.clone());
}
let mut history = match &state.runtime.conversation {
None => vec![Message::User(format!("Begin. {}", state.orchestrator.goal))],
Some(prev) if prev.is_empty() => {
vec![Message::User(format!("Begin. {}", state.orchestrator.goal))]
}
Some(prev) => {
let mut h = prev.clone();
h.push(Message::User(state.orchestrator.goal.clone()));
h
}
};
let goal = match &state.runtime.conversation_goal {
Some(g) => g.as_str(),
None => state.orchestrator.goal.as_str(),
};
let system = self.system_prompt(state, goal);
let mut seen_names = HashSet::new();
if self.research {
seen_names.extend(research_check::identifiers(goal).map(str::to_owned));
seen_names
.extend(research_check::identifiers(&state.orchestrator.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 (outcome, mut report) =
self.run_loop(state, &mut history, &mut seen_names, &system, deadline);
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) {
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)
}
fn run_loop(
&self,
state: &mut State,
history: &mut Vec<Message>,
seen_names: &mut HashSet<String>,
system: &str,
deadline: Option<std::time::Instant>,
) -> (Outcome, RunReport) {
let mut deadline = deadline;
let mut report = RunReport::default();
let specs = tools::specs();
let baseline = self.checkpoint();
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 start_fp = self.fingerprint();
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 pre_dispatch_calls: u32 = 0;
let mut has_dispatched = false;
let mut explore_nudge_sent = false;
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;
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| std::time::Instant::now() >= d) {
return (Outcome::BudgetExhausted, report);
}
if let Some(cap) = state.orchestrator.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);
}
}
}
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(std::time::Instant::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 state.orchestrator.instructions.is_some()
&& state.runtime.conversation.is_none()
&& !has_dispatched
&& !explore_nudge_sent
&& pre_dispatch_calls >= ORCHESTRATOR_EXPLORE_NUDGE
{
explore_nudge_sent = true;
history.push(Message::User(format!(
"You have made {pre_dispatch_calls} tool calls without dispatching. Dispatch the work now from what you know; the implementer reads the code it changes. Keep reading only if you cannot yet say which files the task is about."
)));
}
if !self.research
&& state.orchestrator.instructions.is_none()
&& state.runtime.conversation.is_none()
&& !progressed
{
let elapsed = self.elapsed_fraction(deadline);
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 = std::time::Instant::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(std::time::Instant::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: model_start.elapsed().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| std::time::Instant::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| std::time::Instant::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,
});
if e.is_timeout() {
eprintln!(
"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 {
eprintln!(
"provider: {e}; retrying in {}s ({attempt}/{max_retries})",
wait.as_secs()
);
}
std::thread::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 = model_start.elapsed().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 = std::time::Instant::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| std::time::Instant::now() >= d) {
report.turn_usage.last_mut().unwrap().tools_ms =
tools_start.elapsed().as_millis() as u64;
return (Outcome::BudgetExhausted, report);
}
report.tool_calls += 1;
*report.tool_counts.entry(call.name.clone()).or_default() += 1;
if is_dispatch_call(call) {
has_dispatched = true;
} else if !has_dispatched {
pre_dispatch_calls += 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 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 {
tools::execute_with_deadline(
&self.root,
self.shell,
self.fs,
&call.name,
&call.arguments,
deadline,
)
};
let summary = outcome
.content
.lines()
.next()
.unwrap_or("")
.chars()
.take(90)
.collect::<String>();
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 = 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::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 =
tools_start.elapsed().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 =
tools_start.elapsed().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.orchestrator.verification_cmd.trim().is_empty() {
if state.orchestrator.instructions.is_some() {
return (Outcome::Finished, 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 = std::time::Instant::now();
let (mut passed, mut output, wait_ms, failing) =
self.run_gate(state, &last_failed, &mut deadline);
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(deadline) {
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(gate_start.elapsed().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 {
return (Outcome::Verified, report);
}
report.gate_failures.push(cut_gate_output(&output));
if deadline.is_some_and(|d| std::time::Instant::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 {
self.reset_to(base);
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 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);
}
pieces.join("\n")
}
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}'");
}
}
_ => {}
}
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()
}
}
}