1use std::collections::{BTreeMap, HashMap, HashSet};
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use blyte_provider::{Message, Provider, ProviderError, Request, StreamTiming, Usage, UserPart};
27
28use crate::claim_check;
29use crate::context::ContextStrategy;
30use crate::fs::Fs;
31use crate::gate_slots;
32use crate::quote_expand;
33use crate::research_check;
34use crate::shell::Shell;
35use crate::state::State;
36use crate::tools;
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum Outcome {
41 Verified,
43 Finished,
45 BudgetExhausted,
47 GateFailed,
49 Blocked(String),
51 Error(String),
53}
54
55#[derive(Debug, Clone)]
56pub struct Budget {
57 pub max_turns: u32,
58 pub max_gate_attempts: u32,
59 pub max_duration: Option<Duration>,
62}
63
64impl Default for Budget {
65 fn default() -> Self {
66 Self {
67 max_turns: 60,
68 max_gate_attempts: 5,
69 max_duration: None,
70 }
71 }
72}
73
74#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub struct TurnUsage {
80 pub turn: u32,
81 pub input: u64,
82 pub cached: u64,
83 pub output: u64,
84 pub thinking: u64,
85 pub prompt_messages: usize,
86 pub appended: bool,
87 pub new_chars: usize,
88 #[serde(default)]
90 pub fold_budget: Option<usize>,
91 #[serde(default)]
93 pub model_ms: u64,
94 #[serde(default)]
96 pub tools_ms: u64,
97 #[serde(default)]
100 pub first_data_ms: Option<u64>,
101 #[serde(default)]
103 pub max_gap_ms: u64,
104 #[serde(default, skip_serializing_if = "Vec::is_empty")]
106 pub failed_attempts: Vec<FailedAttempt>,
107}
108
109#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
111pub struct FailedAttempt {
112 pub elapsed_ms: u64,
114 pub timed_out: bool,
116 pub first_data_ms: Option<u64>,
118 pub max_gap_ms: u64,
119}
120
121fn message_chars(m: &Message) -> usize {
123 match m {
124 Message::User(t) | Message::Assistant(t) => t.len(),
125 Message::UserParts(parts) => parts
126 .iter()
127 .map(|p| match p {
128 UserPart::Text(t) => t.len(),
129 UserPart::Image { .. } => crate::context::IMAGE_TOKEN_ESTIMATE * 4,
130 })
131 .sum(),
132 Message::ToolCall { arguments, .. } => arguments.to_string().len(),
133 Message::ToolResult { content, .. } => content.len(),
134 }
135}
136
137#[derive(Debug, Clone, Default)]
138pub struct RunReport {
139 pub outcome_turns: u32,
140 pub usage: Usage,
141 pub empty_turns: u32,
144 pub truncated_turns: u32,
146 pub read_loop: bool,
148 pub peak_read_repeats: u32,
150 pub fold_thrash: bool,
152 pub stalled: bool,
154 pub big_read_turns: u32,
156 pub tool_calls: u32,
157 pub gate_attempts: u32,
158 pub provider_retries: u32,
160 pub turn_usage: Vec<TurnUsage>,
162 pub gate_ms: Vec<u64>,
164 pub gate_turns: Vec<u32>,
166 pub gate_wait_ms: Vec<u64>,
168 pub gate_failures: Vec<String>,
170 pub tool_counts: BTreeMap<String, u32>,
172 pub cost_capped: bool,
174 pub final_message: Option<String>,
176 pub quote_problems: Option<Vec<String>>,
178 pub claim_check: Option<claim_check::ClaimCheck>,
180 pub claim_check_skipped: Option<String>,
182 pub base_check_seconds: Option<f64>,
184 pub base_check_passed: Option<bool>,
186}
187
188#[derive(Debug, Clone)]
194pub enum Event<'e> {
195 FirstOutput {
197 at: std::time::Instant,
198 },
199 Turn {
200 n: u32,
201 text: &'e str,
202 usage: Usage,
203 },
204 ToolStart {
206 name: &'e str,
207 input: String,
208 },
209 Tool {
212 name: &'e str,
213 input: String,
214 summary: String,
215 is_error: bool,
216 },
217 Retry {
219 attempt: u32,
220 max: u32,
221 wait_ms: u64,
222 reason: String,
223 },
224 GateStart {
227 attempt: u32,
228 },
229 GateSlotWait {
231 ms: u64,
232 },
233 Gate {
234 attempt: u32,
235 passed: bool,
236 output: &'e str,
237 },
238 RolledBack {
239 to: &'e str,
240 },
241}
242
243pub const MAX_PROVIDER_RETRIES: u32 = 6;
245
246pub const PEER_MESSAGE_PREFIX: &str = "[blyte] Message from surface ";
247
248pub const CONVERSATION_FIXED: &str = "\
249Change nothing outside the repository yourself (blyte's own files under `.wt/` and its records are fine).\n\n\
250## Working efficiently\n\
251Independent reads, searches and commands can be issued as several tool calls in one \
252turn: they run in order and you see every result together. Batch them whenever one \
253does not depend on another's result; every turn you save is a full model call.\n";
254
255pub const NO_PROGRESS_TURNS: u32 = 20;
257pub const NO_PROGRESS_MIN_TURNS: u32 = 8;
259pub const NO_PROGRESS_TIME_FRACTION: f64 = 0.25;
261pub const LAST_CALL_TURNS: u32 = 10;
263pub const LAST_CALL_TIME_FRACTION: f64 = 0.5;
265
266pub const RESEARCH_FIRST_REPORT_TURN: u32 = 8;
268pub const READ_LOOP_WARN: u32 = 20;
270const READ_LOOP_LIMIT: u32 = 30;
272pub const READ_LOOP_GRACE_TURNS: u32 = 3;
274
275pub const CLAIM_CHECK_RESERVE_MAX: Duration = Duration::from_secs(180);
277
278pub fn claim_check_reserve(max_duration: Duration) -> Duration {
281 (max_duration / 10).min(CLAIM_CHECK_RESERVE_MAX)
282}
283
284fn truncated(reason: Option<&str>) -> bool {
285 matches!(
286 reason,
287 Some("MAX_TOKENS" | "CONTINUATION" | "max_tokens" | "length" | "incomplete")
288 )
289}
290
291fn parse_resets_in_seconds(body: &str) -> Option<u64> {
292 let key = "\"resets_in_seconds\"";
293 let pos = body.find(key)?;
294 let rest = body[pos + key.len()..].trim_start();
295 let after_colon = rest.strip_prefix(':')?.trim_start();
296 let digits: String = after_colon
297 .chars()
298 .take_while(|c| c.is_ascii_digit())
299 .collect();
300 if digits.is_empty() {
301 return None;
302 }
303 digits.parse().ok()
304}
305
306pub fn quota_exhausted(e: &ProviderError) -> Option<String> {
309 let ProviderError::Api { status: 429, body } = e else {
310 return None;
311 };
312 let resets_in_seconds = parse_resets_in_seconds(body);
313 let is_quota = body.contains("usage_limit_reached")
314 || body.contains("insufficient_quota")
315 || body.contains("PerDay")
316 || resets_in_seconds.is_some_and(|s| s > 300);
317
318 if !is_quota {
319 return None;
320 }
321
322 let mut msg = "usage quota exhausted; not retrying".to_string();
323 if let Some(secs) = resets_in_seconds {
324 let human = if secs >= 86400 {
325 format!("{}d {}h", secs / 86400, (secs % 86400) / 3600)
326 } else if secs >= 3600 {
327 format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
328 } else {
329 format!("{}m", secs / 60)
330 };
331 msg.push_str(&format!(" (resets in {human})"));
332 }
333 Some(msg)
334}
335
336pub fn is_transient(e: &ProviderError) -> bool {
339 if quota_exhausted(e).is_some() {
340 return false;
341 }
342 match e {
343 ProviderError::Api { status, .. } => matches!(status, 429 | 500 | 502 | 503 | 504),
344 ProviderError::Transport(_) | ProviderError::NoAnswer { .. } => true,
345 _ => false,
346 }
347}
348
349fn max_retries_for(e: &ProviderError) -> u32 {
350 match e {
351 ProviderError::NoAnswer { .. } => 1,
352 _ => MAX_PROVIDER_RETRIES,
353 }
354}
355
356pub fn retry_delay(attempt: u32) -> Duration {
358 if let Ok(ms) = std::env::var("BLYTE_RETRY_DELAY_MS") {
359 if let Ok(ms) = ms.trim().parse::<u64>() {
360 return Duration::from_millis(ms);
361 }
362 }
363 let exp = attempt.saturating_sub(1).min(5);
364 Duration::from_secs((2u64 << exp).min(60))
365}
366
367pub fn server_retry_hint(e: &ProviderError) -> Option<Duration> {
370 let ProviderError::Api { body, .. } = e else {
371 return None;
372 };
373 let key = "\"retryDelay\"";
374 let rest = &body[body.find(key)? + key.len()..];
375 let value = &rest[rest.find('"')? + 1..];
376 let secs: f64 = value[..value.find('s')?].trim().parse().ok()?;
377 Some(Duration::from_secs_f64(secs.max(0.0)).min(Duration::from_secs(120)))
378}
379
380pub fn retry_wait(e: &ProviderError, attempt: u32) -> Duration {
382 let backoff = retry_delay(attempt);
383 server_retry_hint(e).map_or(backoff, |hint| hint.max(backoff))
384}
385
386#[derive(Debug, Clone, PartialEq, Eq)]
388pub enum BaseCheckState {
389 Pending,
390 Passed,
391 Failed { steps: Vec<String>, tail: String },
392}
393
394pub trait BaseCheckHandle: Sync {
396 fn poll(&self) -> BaseCheckState;
397 fn wait(&self) -> BaseCheckState;
398 fn stop(&self) {}
399 fn elapsed_seconds(&self) -> Option<f64> {
400 None
401 }
402}
403
404#[derive(Default)]
406pub enum BaseCheck<'a> {
407 #[default]
408 None,
409 BeforeFirstTurn,
410 Polled(&'a dyn BaseCheckHandle),
411}
412
413pub fn base_check_tail(output: &str) -> String {
415 let lines: Vec<&str> = output.lines().collect();
416 if lines.len() > 20 {
417 lines[lines.len() - 20..].join("\n")
418 } else {
419 lines.join("\n")
420 }
421}
422
423pub fn base_check_state_from_gate(result: &GateRunResult) -> BaseCheckState {
425 if result.passed {
426 BaseCheckState::Passed
427 } else {
428 BaseCheckState::Failed {
429 steps: result.failures.iter().map(|f| f.step.clone()).collect(),
430 tail: base_check_tail(&result.output),
431 }
432 }
433}
434
435fn base_check_blocked_message(failing_steps: &[String], tail: &str) -> String {
436 let steps = failing_steps.join("; ");
437 format!(
438 "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."
439 )
440}
441
442pub struct Runner<'a> {
443 pub provider: &'a dyn Provider,
444 pub shell: &'a dyn Shell,
445 pub fs: &'a dyn Fs,
446 pub context: &'a dyn ContextStrategy,
447 pub root: PathBuf,
448 pub budget: Budget,
449 pub rollback: bool,
451 pub on_event: Option<&'a dyn Fn(Event<'_>)>,
453 pub research: bool,
455 pub claim_check: bool,
457 pub base_check: BaseCheck<'a>,
459}
460
461const CLAIM_PHRASES: &[&str] = &[
462 "not caused by",
463 "pre-existing",
464 "preexisting",
465 "already fail",
466 "unrelated to",
467 "fails on main",
468 "fails on the base",
469 "was failing before",
470];
471
472fn sh_quote(s: &str) -> String {
473 format!("'{}'", s.replace('\'', r"'\''"))
474}
475
476pub fn read_unless_protected(fs: &dyn Fs, path: &Path) -> Result<String, String> {
477 if fs.is_local() {
478 match crate::sandbox::is_protected_read(path) {
479 Ok(true) => {
480 return Err(format!(
481 "{} is a protected path and is not read",
482 path.display()
483 ));
484 }
485 Ok(false) => {}
486 Err(e) => return Err(e),
487 }
488 }
489 fs.read(path)
490}
491
492impl<'a> Runner<'a> {
493 fn emit(&self, e: Event<'_>) {
494 if let Some(f) = self.on_event {
495 f(e)
496 }
497 }
498}
499
500impl<'a> Runner<'a> {
501 fn system_prompt(&self, state: &State, goal: Option<&str>) -> Result<String, String> {
505 let bins = tools::available_binaries(self.shell, &self.root)?.join(", ");
506 let where_ = self.shell.describe();
507
508 if let Some(text) = &state.brief.instructions {
509 let request_section = match goal {
510 Some(goal) => format!("## Your user's first request\n{goal}\n\n"),
511 None => String::new(),
512 };
513 return Ok(format!(
514 "{text}{request_section}\
515 ## Environment\n{where_}\nAvailable: {bins}\n\n\
516 {CONVERSATION_FIXED}",
517 ));
518 }
519
520 let rules = crate::rules::prompt_section(&self.root);
521
522 let steps = gate_steps(&state.brief.verification_cmd);
523 let completion = if steps.is_empty() {
525 "No command checks your work. When you stop, the result is judged by tests you \
526 cannot see, so verify it yourself first: run the project's existing test suite and \
527 the tests that cover your change, and check the edge cases the task describes. \
528 If you searched for problems (with grep or other commands), run those same searches \
529 again before you stop and confirm they find nothing left to fix. Stop \
530 only when you are confident the task is complete."
531 .to_string()
532 } else {
533 let verify = steps.join(" && ");
534 format!(
535 "Your work is accepted when `{verify}` exits 0. That command is run for you when \
536 you stop calling tools, and you do not decide the verdict. A failure costs a full \
537 rerun after your fix, so before you stop, run its quick parts yourself \
538 (formatting, lint) together with the tests that cover your change; leave the slow \
539 full run to it. Do not claim to be finished; simply stop when you believe the \
540 command will pass, and you will be told."
541 )
542 };
543 Ok(format!(
544 "You are a software engineer working in a repository.\n\n\
545 ## Goal\n{goal}\n\n\
546 ## How completion is decided\n\
547 {completion}\n\n\
548 ## Environment\n{where_}\nAvailable: {bins}\n\n\
549 Change nothing outside the repository: no caches, other repositories, \
550 home-directory files or system settings. If something outside it blocks you \
551 (disk space, network, a missing tool), say so and stop.\n\n\
552 {rules}\
553 ## Working efficiently\n\
554 Independent reads, searches and commands can be issued as several tool calls in one \
555 turn: they run in order and you see every result together. Batch them whenever one \
556 does not depend on another's result; every turn you save is a full model call.\n",
557 goal = goal.unwrap_or(&state.brief.goal),
558 completion = completion,
559 where_ = where_,
560 bins = bins,
561 rules = rules,
562 ))
563 }
564
565 fn run_gate(
571 &self,
572 state: &State,
573 last_failed: &[String],
574 deadline: &mut Option<std::time::Instant>,
575 now: &(dyn Fn() -> std::time::Instant + Sync),
576 ) -> (bool, String, u64, Vec<String>) {
577 let result = run_gate_steps(
578 self.shell,
579 &state.brief.verification_cmd,
580 &self.root,
581 last_failed,
582 deadline,
583 |ms| self.emit(Event::GateSlotWait { ms }),
584 now,
585 );
586 let failed = result.failures.into_iter().map(|f| f.step).collect();
587 (result.passed, result.output, result.wait_ms, failed)
588 }
589
590 fn run_step_in(
591 &self,
592 cmd: &str,
593 dir: &Path,
594 deadline: Option<std::time::Instant>,
595 now: &(dyn Fn() -> std::time::Instant + Sync),
596 ) -> (bool, String) {
597 run_gate_step(self.shell, cmd, dir, deadline, now)
598 }
599
600 fn fingerprint(&self) -> Option<String> {
601 let head = self
602 .shell
603 .exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
604 .ok()?;
605 if head.exit_code != 0 {
606 return None;
607 }
608 let status = self
609 .shell
610 .exec(
611 "git status --porcelain",
612 &self.root,
613 Duration::from_secs(30),
614 )
615 .ok()?;
616 if status.exit_code != 0 {
617 return None;
618 }
619 Some(format!("{}\n{}", head.stdout, status.stdout))
620 }
621
622 fn check_blocked_at_base(&self, base_commit: &str, failing_steps: &[String]) -> bool {
623 if failing_steps.is_empty() {
624 return false;
625 }
626
627 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
628 let unique = format!(
629 "blyte-base-{}-{}-{}",
630 std::process::id(),
631 std::time::SystemTime::now()
632 .duration_since(std::time::UNIX_EPOCH)
633 .map(|d| d.as_nanos())
634 .unwrap_or(0),
635 COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
636 );
637 let wt_path = std::env::temp_dir().join(unique);
638
639 let add_cmd = format!(
640 "git worktree add --detach {} {}",
641 sh_quote(&wt_path.to_string_lossy()),
642 sh_quote(base_commit)
643 );
644 let add_out = match self
645 .shell
646 .exec(&add_cmd, &self.root, Duration::from_secs(60))
647 {
648 Ok(o) if o.exit_code == 0 => o,
649 _ => return false,
650 };
651 let _ = add_out;
652
653 struct Guard<'a> {
654 shell: &'a dyn Shell,
655 root: &'a Path,
656 path: PathBuf,
657 }
658 impl<'a> Drop for Guard<'a> {
659 fn drop(&mut self) {
660 let cmd = format!(
661 "git worktree remove --force {}",
662 sh_quote(&self.path.to_string_lossy())
663 );
664 let _ = self.shell.exec(&cmd, self.root, Duration::from_secs(60));
665 let _ = std::fs::remove_dir_all(&self.path);
666 }
667 }
668
669 let _guard = Guard {
670 shell: self.shell,
671 root: &self.root,
672 path: wt_path.clone(),
673 };
674
675 let mut all_failed = true;
676 for step in failing_steps {
677 let (passed, _) = self.run_step_in(step, &wt_path, None, &std::time::Instant::now);
678 if passed {
679 all_failed = false;
680 }
681 }
682 all_failed
683 }
684
685 fn checkpoint(&self) -> Option<String> {
686 let out = self
687 .shell
688 .exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
689 .ok()?;
690 (out.exit_code == 0).then(|| out.stdout.trim().to_string())
691 }
692
693 fn check_report_quotes(&self, seen_names: &HashSet<String>) -> Vec<String> {
695 let Ok(raw) = self.fs.read(&self.root.join("report.md")) else {
696 return Vec::new();
697 };
698 let expand_read = |p: &Path| {
701 let allowed = tools::resolve_for_read(self.fs, &self.root, &p.to_string_lossy())?;
702 read_unless_protected(self.fs, &allowed)
703 };
704 let (report, mut problems) = quote_expand::expand(&raw, &expand_read);
705 if report != raw {
706 if let Err(e) = self.fs.write(&self.root.join("report.md"), &report) {
707 problems.push(format!(
708 "report.md: could not write the expanded quotes: {e}"
709 ));
710 }
711 }
712 let read_roots = tools::read_roots();
713 let mut listing = Vec::new();
714 for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
717 if let Ok(o) = self.shell.exec(
718 "git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
719 dir,
720 Duration::from_secs(60),
721 ) {
722 if o.exit_code == 0 {
723 listing.extend(o.stdout.lines().map(|l| dir.join(l)));
724 }
725 }
726 }
727 let read = |p: &Path| read_unless_protected(self.fs, p);
728 let sources = research_check::Sources {
729 workspace: &self.root,
730 read_roots: &read_roots,
731 listing: &listing,
732 read: &read,
733 };
734 problems.extend(research_check::check(&report, &sources));
735 problems.extend(research_check::unseen_names(&report, seen_names));
736 problems.extend(research_check::unseen_paths(&report, &sources, seen_names));
737 problems
738 }
739
740 fn run_claim_check(
741 &self,
742 redactor: &crate::redact::Redactor,
743 deadline: Option<std::time::Instant>,
744 now: &(dyn Fn() -> std::time::Instant + Sync),
745 ) -> Option<claim_check::ClaimCheck> {
746 if !self.claim_check {
747 return None;
748 }
749 let report = self.fs.read(&self.root.join("report.md")).ok()?;
750 if report.is_empty() {
751 return None;
752 }
753 let read_roots = tools::read_roots();
754 let mut listing = Vec::new();
755 for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
756 if let Ok(o) = self.shell.exec(
757 "git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
758 dir,
759 Duration::from_secs(60),
760 ) {
761 if o.exit_code == 0 {
762 listing.extend(o.stdout.lines().map(|l| dir.join(l)));
763 }
764 }
765 }
766 let read = |p: &Path| read_unless_protected(self.fs, p);
767 let claims = research_check::claims(
768 &report,
769 &research_check::Sources {
770 workspace: &self.root,
771 read_roots: &read_roots,
772 listing: &listing,
773 read: &read,
774 },
775 );
776 Some(claim_check::check_claims_with_clock(
777 self.provider,
778 redactor,
779 &claims,
780 deadline,
781 now,
782 ))
783 }
784
785 fn reset_to(&self, commit: &str) -> Result<(), String> {
786 let out = self
787 .shell
788 .exec(
789 &format!("git reset --hard {commit} && git clean -fd"),
790 &self.root,
791 Duration::from_secs(120),
792 )
793 .map_err(|e| format!("could not roll back to {commit}: {e}"))?;
794 if out.exit_code != 0 {
795 let detail = out.merged();
796 let detail = detail.trim();
797 return if detail.is_empty() {
798 Err(format!(
799 "could not roll back to {commit}: exit {}",
800 out.exit_code
801 ))
802 } else {
803 Err(format!(
804 "could not roll back to {commit}: exit {}: {detail}",
805 out.exit_code
806 ))
807 };
808 }
809 Ok(())
810 }
811
812 fn elapsed_fraction(
813 &self,
814 deadline: Option<std::time::Instant>,
815 now: &(dyn Fn() -> std::time::Instant + Sync),
816 ) -> Option<f64> {
817 let max_duration = self.budget.max_duration?;
818 let deadline = deadline?;
819 let remaining = deadline.saturating_duration_since(now());
820 Some(max_duration.saturating_sub(remaining).as_secs_f64() / max_duration.as_secs_f64())
821 }
822
823 pub fn run(&self, state: &mut State) -> (Outcome, RunReport) {
824 self.run_with_clock(state, &std::time::Instant::now)
825 }
826
827 pub fn run_with_clock(
829 &self,
830 state: &mut State,
831 now: &(dyn Fn() -> std::time::Instant + Sync),
832 ) -> (Outcome, RunReport) {
833 self.run_until(state, now, &std::thread::sleep)
834 }
835
836 pub fn run_with_clock_and_sleep(
838 &self,
839 state: &mut State,
840 now: &(dyn Fn() -> std::time::Instant + Sync),
841 sleep: &(dyn Fn(std::time::Duration) + Sync),
842 ) -> (Outcome, RunReport) {
843 self.run_until(state, now, sleep)
844 }
845
846 fn run_until(
847 &self,
848 state: &mut State,
849 now: &(dyn Fn() -> std::time::Instant + Sync),
850 sleep: &(dyn Fn(std::time::Duration) + Sync),
851 ) -> (Outcome, RunReport) {
852 if state.runtime.conversation.is_some()
853 && state.runtime.conversation_goal.is_none()
854 && !state.brief.goal.starts_with(PEER_MESSAGE_PREFIX)
855 {
856 state.runtime.conversation_goal = Some(state.brief.goal.clone());
857 }
858
859 let pending = std::mem::take(&mut state.runtime.pending_user_parts);
860 let make_user_message = |prompt: String| {
861 if pending.is_empty() {
862 Message::User(prompt)
863 } else {
864 let mut parts = Vec::with_capacity(1 + pending.len());
865 parts.push(UserPart::Text(prompt));
866 parts.extend(pending);
867 Message::UserParts(parts)
868 }
869 };
870
871 let mut history = match &state.runtime.conversation {
872 None => vec![make_user_message(format!("Begin. {}", state.brief.goal))],
873 Some(prev) if prev.is_empty() => {
874 vec![make_user_message(format!("Begin. {}", state.brief.goal))]
875 }
876 Some(prev) => {
877 let mut h = prev.clone();
878 h.push(make_user_message(state.brief.goal.clone()));
879 h
880 }
881 };
882
883 let goal = match &state.runtime.conversation_goal {
884 Some(g) => Some(g.as_str()),
885 None if state.brief.goal.starts_with(PEER_MESSAGE_PREFIX) => None,
886 None => Some(state.brief.goal.as_str()),
887 };
888 let system = match self.system_prompt(state, goal) {
889 Ok(s) => s,
890 Err(err) => {
891 if let BaseCheck::Polled(handle) = self.base_check {
892 handle.stop();
893 }
894 if state.runtime.conversation.is_some() {
895 state.runtime.conversation = Some(history);
896 }
897 return (Outcome::Error(err), RunReport::default());
898 }
899 };
900 let redactor = match crate::redact::Redactor::for_root(&self.root) {
901 Ok(r) => r,
902 Err(err) => {
903 if let BaseCheck::Polled(handle) = self.base_check {
904 handle.stop();
905 }
906 if state.runtime.conversation.is_some() {
907 state.runtime.conversation = Some(history);
908 }
909 return (Outcome::Error(err), RunReport::default());
910 }
911 };
912
913 let mut seen_names = HashSet::new();
914 if self.research {
915 if let Some(g) = goal {
916 seen_names.extend(research_check::identifiers(g).map(str::to_owned));
917 }
918 seen_names.extend(research_check::identifiers(&state.brief.goal).map(str::to_owned));
919 for msg in &history {
922 if let Message::ToolResult { content, .. } = msg {
923 seen_names.extend(research_check::identifiers(content).map(str::to_owned));
924 }
925 }
926 }
927
928 let baseline = self.checkpoint();
929 let start_fp = self.fingerprint();
930 let deadline = self.budget.max_duration.map(|d| now() + d);
931
932 let loop_deadline = match (
933 self.research && self.claim_check,
934 deadline,
935 self.budget.max_duration,
936 ) {
937 (true, Some(d), Some(max_d)) => d.checked_sub(claim_check_reserve(max_d)).or(deadline),
938 _ => deadline,
939 };
940
941 let (outcome, mut report) = self.run_loop(
942 state,
943 &mut history,
944 &mut seen_names,
945 &system,
946 &redactor,
947 baseline,
948 start_fp,
949 loop_deadline,
950 deadline,
951 now,
952 sleep,
953 );
954 if let BaseCheck::Polled(handle) = self.base_check {
955 if outcome != Outcome::Verified && report.base_check_passed.is_none() {
956 match handle.poll() {
957 BaseCheckState::Pending => {
958 handle.stop();
959 }
960 BaseCheckState::Passed => {
961 report.base_check_passed = Some(true);
962 report.base_check_seconds = handle.elapsed_seconds();
963 }
964 BaseCheckState::Failed { .. } => {
965 report.base_check_passed = Some(false);
966 report.base_check_seconds = handle.elapsed_seconds();
967 }
968 }
969 }
970 }
971 if self.research
972 && outcome != Outcome::Verified
973 && self
974 .fs
975 .read(&self.root.join("report.md"))
976 .is_ok_and(|s| !s.is_empty())
977 {
978 if report.quote_problems.is_none() {
979 let mut problems = self.check_report_quotes(&seen_names);
980 problems.truncate(research_check::MAX_PROBLEMS);
981 report.quote_problems = Some(problems);
982 }
983 if report.claim_check.is_none() && report.claim_check_skipped.is_none() {
984 if let Some(cc) = self.run_claim_check(&redactor, deadline, now) {
985 report.usage.input += cc.usage.input;
986 report.usage.cached += cc.usage.cached;
987 report.usage.output += cc.usage.output;
988 report.usage.thinking += cc.usage.thinking;
989 report.claim_check_skipped = cc.skipped.clone();
990 if cc.calls > 0 || cc.skipped.is_none() {
991 report.claim_check = Some(cc);
992 }
993 }
994 }
995 }
996
997 if state.runtime.conversation.is_some() {
998 state.runtime.conversation = Some(history);
999 }
1000
1001 (outcome, report)
1002 }
1003
1004 #[allow(clippy::too_many_arguments)]
1005 fn run_loop(
1006 &self,
1007 state: &mut State,
1008 history: &mut Vec<Message>,
1009 seen_names: &mut HashSet<String>,
1010 system: &str,
1011 redactor: &crate::redact::Redactor,
1012 baseline: Option<String>,
1013 start_fp: Option<String>,
1014 deadline: Option<std::time::Instant>,
1015 claim_deadline: Option<std::time::Instant>,
1016 now: &(dyn Fn() -> std::time::Instant + Sync),
1017 sleep: &(dyn Fn(std::time::Duration) + Sync),
1018 ) -> (Outcome, RunReport) {
1019 let mut deadline = deadline;
1020 let mut report = RunReport::default();
1021 let specs = tools::specs();
1022 let mut last_sent: Option<Vec<Message>> = None;
1023 let mut last_failed: Vec<String> = Vec::new();
1024 let mut last_fingerprint: Option<String> = None;
1025 let mut call_counts: HashMap<String, u32> = HashMap::new();
1026 let mut repeats: u32 = 0;
1027 let mut read_warn_sent = false;
1028 let mut read_loop_turn: Option<u32> = None;
1029 let mut change_fp = start_fp.clone();
1030 let mut progressed = false;
1031 let mut nudge_turn: Option<u32> = None;
1032 let mut last_call_sent = false;
1033 let mut last_turn_called_tools = false;
1034 let mut last_report = if self.research {
1035 self.fs.read(&self.root.join("report.md")).ok()
1036 } else {
1037 None
1038 };
1039 let mut claim_round_done = false;
1040 let mut prev_turn_start: Option<usize> = None;
1041 let mut thrash: u32 = 0;
1042 let mut last_big_read_warn: Option<u32> = None;
1043 let mut wrap_up_sent = false;
1044 let mut wrap_up_tools_closed = false;
1045 let mut wrap_up_report: Option<String> = None;
1046
1047 if matches!(self.base_check, BaseCheck::BeforeFirstTurn)
1048 && !gate_steps(&state.brief.verification_cmd).is_empty()
1049 {
1050 let bc_start = now();
1051 let (passed, output, _wait_ms, failing_steps) =
1052 self.run_gate(state, &[], &mut deadline, now);
1053 report.base_check_seconds =
1054 Some(now().saturating_duration_since(bc_start).as_secs_f64());
1055 report.base_check_passed = Some(passed);
1056 if !passed {
1057 let tail = base_check_tail(&output);
1058 let msg = base_check_blocked_message(&failing_steps, &tail);
1059 report.final_message = Some(msg.clone());
1060 return (Outcome::Blocked(msg), report);
1061 }
1062 }
1063
1064 for turn in 1..=self.budget.max_turns {
1065 if read_loop_turn.is_some_and(|t| turn > t + READ_LOOP_GRACE_TURNS) {
1066 return (Outcome::BudgetExhausted, report);
1067 }
1068 if deadline.is_some_and(|d| now() >= d) {
1069 return (Outcome::BudgetExhausted, report);
1070 }
1071 if let Some(cap) = state.brief.max_cost_usd {
1072 if let Some(price) = blyte_provider::pricing(&self.provider.model_id()) {
1073 if price.cost(&report.usage) >= cap {
1074 report.cost_capped = true;
1075 return (Outcome::BudgetExhausted, report);
1076 }
1077 }
1078 }
1079 if let BaseCheck::Polled(handle) = self.base_check {
1080 if report.base_check_passed.is_none() {
1081 match handle.poll() {
1082 BaseCheckState::Pending => {}
1083 BaseCheckState::Passed => {
1084 report.base_check_passed = Some(true);
1085 report.base_check_seconds = handle.elapsed_seconds();
1086 }
1087 BaseCheckState::Failed { steps, tail } => {
1088 report.base_check_passed = Some(false);
1089 report.base_check_seconds = handle.elapsed_seconds();
1090 let msg = base_check_blocked_message(&steps, &tail);
1091 report.final_message = Some(msg.clone());
1092 return (Outcome::Blocked(msg), report);
1093 }
1094 }
1095 }
1096 }
1097 report.outcome_turns = turn;
1098 let turn_start = history.len();
1099
1100 if !wrap_up_sent {
1101 if self.budget.max_turns >= 20 && turn == self.budget.max_turns - 9 {
1102 wrap_up_sent = true;
1103 history.push(Message::User(format!(
1104 "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.",
1105 self.budget.max_turns
1106 )));
1107 } else if let (Some(max_duration), Some(deadline)) =
1108 (self.budget.max_duration, deadline)
1109 {
1110 let time_left = deadline.saturating_duration_since(now());
1111 if time_left.as_secs_f64() < max_duration.as_secs_f64() * 0.1 {
1112 wrap_up_sent = true;
1113 let m = ((time_left.as_secs_f64() / 60.0).ceil() as u64).max(1);
1114 let total = ((max_duration.as_secs_f64() / 60.0).ceil() as u64).max(1);
1115 history.push(Message::User(format!(
1116 "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."
1117 )));
1118 }
1119 }
1120 if wrap_up_sent && self.research {
1121 wrap_up_tools_closed = true;
1122 wrap_up_report = self.fs.read(&self.root.join("report.md")).ok();
1123 }
1124 }
1125
1126 if self.research && turn == RESEARCH_FIRST_REPORT_TURN {
1127 let has_report = self
1128 .fs
1129 .read(&self.root.join("report.md"))
1130 .is_ok_and(|s| !s.trim().is_empty());
1131 if !has_report {
1132 history.push(Message::User(
1133 "Start report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
1134 ));
1135 }
1136 }
1137
1138 if self.research && turn % 30 == 0 {
1139 let current_report = self.fs.read(&self.root.join("report.md")).ok();
1140 if current_report == last_report {
1141 history.push(Message::User(
1142 "Update report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
1143 ));
1144 }
1145 last_report = current_report;
1146 }
1147
1148 if !self.research
1149 && state.brief.instructions.is_none()
1150 && state.runtime.conversation.is_none()
1151 && !progressed
1152 {
1153 let elapsed = self.elapsed_fraction(deadline, now);
1154 if nudge_turn.is_none()
1155 && (turn > NO_PROGRESS_TURNS
1156 || (turn > NO_PROGRESS_MIN_TURNS
1157 && elapsed.is_some_and(|f| f >= NO_PROGRESS_TIME_FRACTION)))
1158 {
1159 if self.fingerprint() != start_fp {
1160 progressed = true;
1161 } else {
1162 let n = turn - 1;
1163 history.push(Message::User(format!(
1164 "[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."
1165 )));
1166 nudge_turn = Some(turn);
1167 }
1168 } else if let Some(t) = nudge_turn {
1169 if !last_call_sent
1170 && (turn >= t + LAST_CALL_TURNS
1171 || elapsed.is_some_and(|f| f >= LAST_CALL_TIME_FRACTION))
1172 {
1173 if self.fingerprint() != start_fp {
1174 progressed = true;
1175 } else {
1176 history.push(Message::User(
1177 "[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."
1178 .to_string(),
1179 ));
1180 last_call_sent = true;
1181 }
1182 } else if last_call_sent && last_turn_called_tools {
1183 if self.fingerprint() != start_fp {
1184 progressed = true;
1185 } else {
1186 report.stalled = true;
1187 return (Outcome::BudgetExhausted, report);
1188 }
1189 }
1190 }
1191 }
1192
1193 let fold_budget = self.context.fold_budget(history);
1194 if let Some(prev_start) = prev_turn_start {
1195 if let Some(budget) = fold_budget {
1196 let n: usize = history[prev_start..]
1197 .iter()
1198 .filter(|m| matches!(m, Message::ToolResult { .. }))
1199 .map(crate::context::approx_tokens)
1200 .sum();
1201 if n > budget / 2 {
1202 report.big_read_turns += 1;
1203 if last_big_read_warn.is_none_or(|last| turn >= last + 5) {
1204 last_big_read_warn = Some(turn);
1205 history.push(Message::User(format!(
1206 "[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."
1207 )));
1208 }
1209 }
1210 }
1211 if self
1212 .context
1213 .folds(history)
1214 .last()
1215 .is_some_and(|&(_, b)| b + 1 > prev_start)
1216 {
1217 thrash += 1;
1218 if thrash >= 5 {
1219 report.fold_thrash = true;
1220 return (Outcome::BudgetExhausted, report);
1221 }
1222 if thrash == 2 {
1223 let budget = fold_budget.unwrap_or_default();
1224 history.push(Message::User(format!(
1225 "[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."
1226 )));
1227 }
1228 } else {
1229 thrash = 0;
1230 }
1231 }
1232 prev_turn_start = Some(turn_start);
1233
1234 let mut req = Request {
1235 system: system.to_string(),
1236 messages: self.context.build(state, history),
1237 tools: specs.clone(),
1238 max_output_tokens: None,
1239 timeout: None,
1240 };
1241 let (appended, new_chars) = match &last_sent {
1242 Some(prev)
1243 if req.messages.len() >= prev.len()
1244 && req.messages[..prev.len()] == prev[..] =>
1245 {
1246 (
1247 true,
1248 req.messages[prev.len()..].iter().map(message_chars).sum(),
1249 )
1250 }
1251 _ => (false, req.messages.iter().map(message_chars).sum()),
1252 };
1253 last_sent = Some(req.messages.clone());
1254 let mut sent_req = redactor.redact_request(&req);
1257 let model_start = now();
1258 let mut attempt = 0;
1259 let mut failed_attempts: Vec<FailedAttempt> = Vec::new();
1260 let (resp, call_start) = loop {
1261 if let Some(d) = deadline {
1262 let time_left = d.saturating_duration_since(now());
1263 if time_left.is_zero() {
1264 return (Outcome::BudgetExhausted, report);
1265 }
1266 req.timeout = Some(time_left);
1267 sent_req.timeout = Some(time_left);
1268 }
1269 let call_start = std::time::Instant::now();
1270 match self.provider.complete(&sent_req) {
1271 Ok(r) => break (r, call_start),
1272 Err(e) => {
1273 let (u_in, u_cached, u_out, u_think) = match &e {
1274 ProviderError::NoAnswer { usage, .. } => {
1275 report.usage.input += usage.input;
1276 report.usage.cached += usage.cached;
1277 report.usage.output += usage.output;
1278 report.usage.thinking += usage.thinking;
1279 (usage.input, usage.cached, usage.output, usage.thinking)
1280 }
1281 _ => (0, 0, 0, 0),
1282 };
1283 let push_deadline_turn = |report: &mut RunReport| {
1284 let timing = self.provider.last_stream_timing().unwrap_or_default();
1285 report.turn_usage.push(TurnUsage {
1286 turn,
1287 input: u_in,
1288 cached: u_cached,
1289 output: u_out,
1290 thinking: u_think,
1291 prompt_messages: req.messages.len(),
1292 appended,
1293 new_chars,
1294 fold_budget,
1295 model_ms: now().saturating_duration_since(model_start).as_millis()
1296 as u64,
1297 tools_ms: 0,
1298 first_data_ms: timing.first_data_ms,
1299 max_gap_ms: timing.max_gap_ms,
1300 failed_attempts: failed_attempts.clone(),
1301 });
1302 };
1303 if quota_exhausted(&e).is_none() && deadline.is_some_and(|d| now() >= d) {
1306 push_deadline_turn(&mut report);
1307 return (Outcome::BudgetExhausted, report);
1308 }
1309 let max_retries = max_retries_for(&e);
1310 if is_transient(&e) && attempt < max_retries {
1311 let elapsed = call_start.elapsed().as_secs_f64().round() as u64;
1312 let s = if elapsed > 0 {
1313 elapsed
1314 } else {
1315 blyte_provider::model_timeout_secs()
1316 };
1317 attempt += 1;
1318 let wait = retry_wait(&e, attempt);
1319 if deadline.is_some_and(|d| now() + wait >= d) {
1320 push_deadline_turn(&mut report);
1321 return (Outcome::BudgetExhausted, report);
1322 }
1323 report.provider_retries += 1;
1324 let timing = self.provider.last_stream_timing().unwrap_or_default();
1325 failed_attempts.push(FailedAttempt {
1326 elapsed_ms: call_start.elapsed().as_millis() as u64,
1327 timed_out: e.is_timeout(),
1328 first_data_ms: timing.first_data_ms,
1329 max_gap_ms: timing.max_gap_ms,
1330 });
1331 let reason = if e.is_timeout() {
1332 format!(
1333 "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)"
1334 )
1335 } else {
1336 format!(
1337 "provider: {e}; retrying in {}s ({attempt}/{max_retries})",
1338 wait.as_secs()
1339 )
1340 };
1341 eprintln!("{reason}");
1342 self.emit(Event::Retry {
1343 attempt,
1344 max: max_retries,
1345 wait_ms: wait.as_millis() as u64,
1346 reason,
1347 });
1348 sleep(wait);
1349 } else {
1350 let err_msg = match quota_exhausted(&e) {
1351 Some(msg) => format!("{msg}: {e}"),
1352 None => e.to_string(),
1353 };
1354 return (Outcome::Error(err_msg), report);
1355 }
1356 }
1357 }
1358 };
1359 let model_ms = now().saturating_duration_since(model_start).as_millis() as u64;
1360 let timing: StreamTiming = self.provider.last_stream_timing().unwrap_or_default();
1361 report.usage.input += resp.usage.input;
1362 report.usage.cached += resp.usage.cached;
1363 report.usage.output += resp.usage.output;
1364 report.usage.thinking += resp.usage.thinking;
1365 report.turn_usage.push(TurnUsage {
1366 turn,
1367 input: resp.usage.input,
1368 cached: resp.usage.cached,
1369 output: resp.usage.output,
1370 thinking: resp.usage.thinking,
1371 prompt_messages: req.messages.len(),
1372 appended,
1373 new_chars,
1374 fold_budget,
1375 model_ms,
1376 tools_ms: 0,
1377 first_data_ms: timing.first_data_ms,
1378 max_gap_ms: timing.max_gap_ms,
1379 failed_attempts,
1380 });
1381
1382 let has_output = !resp.text.is_empty()
1383 || !resp.tool_calls.is_empty()
1384 || resp.usage.output > 0
1385 || resp.usage.thinking > 0;
1386 if has_output {
1387 if let Some(first_data_ms) = timing.first_data_ms {
1388 let at = (call_start + Duration::from_millis(first_data_ms))
1389 .min(std::time::Instant::now());
1390 self.emit(Event::FirstOutput { at });
1391 }
1392 }
1393
1394 let trimmed = resp.text.trim();
1395 self.emit(Event::Turn {
1396 n: turn,
1397 text: trimmed,
1398 usage: resp.usage,
1399 });
1400 if truncated(resp.finish_reason.as_deref()) {
1401 last_turn_called_tools = false;
1402 report.truncated_turns += 1;
1403 history.push(Message::User(
1404 "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(),
1405 ));
1406 continue;
1407 }
1408 if trimmed.is_empty() && resp.tool_calls.is_empty() {
1409 report.empty_turns += 1;
1410 }
1411 if !trimmed.is_empty() {
1412 report.final_message = Some(trimmed.to_string());
1413 history.push(Message::Assistant(resp.text.clone()));
1414 }
1415
1416 if !resp.tool_calls.is_empty() {
1418 last_turn_called_tools = true;
1419 let tools_start = now();
1420 for call in &resp.tool_calls {
1425 history.push(Message::ToolCall {
1426 id: call.id.clone(),
1427 name: call.name.clone(),
1428 arguments: call.arguments.clone(),
1429 signature: call.signature.clone(),
1430 });
1431 }
1432 let current_fp = self.fingerprint();
1433 if current_fp != start_fp {
1434 progressed = true;
1435 }
1436 if current_fp != change_fp {
1437 call_counts.clear();
1438 repeats = 0;
1439 read_warn_sent = false;
1440 change_fp = current_fp;
1441 }
1442 for call in &resp.tool_calls {
1443 if deadline.is_some_and(|d| now() >= d) {
1444 report.turn_usage.last_mut().unwrap().tools_ms =
1445 now().saturating_duration_since(tools_start).as_millis() as u64;
1446 return (Outcome::BudgetExhausted, report);
1447 }
1448 report.tool_calls += 1;
1449 *report.tool_counts.entry(call.name.clone()).or_default() += 1;
1450
1451 if wrap_up_tools_closed
1452 && self
1453 .fs
1454 .read(&self.root.join("report.md"))
1455 .ok()
1456 .is_some_and(|s| {
1457 !s.is_empty() && Some(s.as_str()) != wrap_up_report.as_deref()
1458 })
1459 {
1460 wrap_up_tools_closed = false;
1461 }
1462 let read_closed = read_loop_turn.is_some()
1463 && matches!(call.name.as_str(), "read" | "grep" | "glob");
1464 let wrap_up_closed =
1465 wrap_up_tools_closed && !matches!(call.name.as_str(), "write" | "edit");
1466 let tool_closed = read_closed || wrap_up_closed;
1467 let input = if call.name == "read" {
1468 extract_action_target(&call.name, &call.arguments)
1469 .chars()
1470 .take(100)
1471 .collect()
1472 } else {
1473 let clean = |s: &str| s.trim_end().replace('\n', " ↵ ");
1474 let text = if call.name == "blyte" {
1475 format_blyte_tool_input(&call.arguments)
1476 .map(|s| clean(&s))
1477 .unwrap_or_else(|| clean(&call.arguments.to_string()))
1478 } else {
1479 call.arguments
1480 .get("command")
1481 .or_else(|| call.arguments.get("pattern"))
1482 .or_else(|| call.arguments.get("path"))
1483 .and_then(|v| v.as_str())
1484 .map(clean)
1485 .unwrap_or_else(|| clean(&call.arguments.to_string()))
1486 };
1487 if text.chars().count() > 2000 {
1488 let mut cut: String = text.chars().take(2000).collect();
1489 cut.push('…');
1490 cut
1491 } else {
1492 text
1493 }
1494 };
1495 self.emit(Event::ToolStart {
1496 name: &call.name,
1497 input: input.clone(),
1498 });
1499 let mut outcome = if read_closed {
1500 tools::ToolOutcome {
1501 content: "[blyte] reading is closed; write report.md now from what you have found.".to_string(),
1502 is_error: true,
1503 }
1504 } else if wrap_up_closed {
1505 tools::ToolOutcome {
1506 content: "[blyte] almost out of budget: write report.md now (write or edit). Other tools are closed until report.md has changed.".to_string(),
1507 is_error: true,
1508 }
1509 } else {
1510 let tool_timeout = deadline
1511 .map(|d| d.saturating_duration_since(now()))
1512 .unwrap_or(Duration::MAX);
1515 tools::execute_with_timeout(
1516 &self.root,
1517 self.shell,
1518 self.fs,
1519 &call.name,
1520 &call.arguments,
1521 tool_timeout,
1522 )
1523 };
1524
1525 let summary = outcome
1526 .content
1527 .lines()
1528 .next()
1529 .unwrap_or("")
1530 .chars()
1531 .take(90)
1532 .collect::<String>();
1533 self.emit(Event::Tool {
1534 name: &call.name,
1535 input,
1536 summary,
1537 is_error: outcome.is_error,
1538 });
1539
1540 if self.research && !tool_closed {
1541 seen_names.extend(
1542 research_check::identifiers(&outcome.content).map(str::to_owned),
1543 );
1544 }
1545 if !outcome.is_error && matches!(call.name.as_str(), "edit" | "write") {
1546 progressed = true;
1547 call_counts.clear();
1548 repeats = 0;
1549 read_warn_sent = false;
1550 } else if !tool_closed && matches!(call.name.as_str(), "read" | "grep" | "glob")
1551 {
1552 let key = format!("{}:{}", call.name, call.arguments);
1553 let n = call_counts.entry(key).or_insert(0);
1554 *n += 1;
1555 let n = *n;
1556 if n >= 2 {
1557 repeats += 1;
1558 report.peak_read_repeats = report.peak_read_repeats.max(repeats);
1559 }
1560 if n >= 3 {
1561 let tail = if self.research {
1562 "write what you need into report.md"
1563 } else {
1564 "and make your change"
1565 };
1566 outcome.content.push_str(&format!(
1567 "\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}."
1568 ));
1569 }
1570 if self.research && !read_warn_sent && repeats >= READ_LOOP_WARN {
1571 read_warn_sent = true;
1572 outcome.content.push_str(&format!(
1573 "\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}."
1574 ));
1575 }
1576 }
1577 history.push(Message::ToolResult {
1578 id: call.id.clone(),
1579 name: call.name.clone(),
1580 content: outcome.content,
1581 is_error: outcome.is_error,
1582 });
1583 if repeats >= READ_LOOP_LIMIT && read_loop_turn.is_none() {
1584 report.read_loop = true;
1585 if !self.research {
1586 report.turn_usage.last_mut().unwrap().tools_ms =
1587 now().saturating_duration_since(tools_start).as_millis() as u64;
1588 return (Outcome::BudgetExhausted, report);
1589 }
1590 read_loop_turn = Some(turn);
1591 }
1592 }
1593 if read_loop_turn == Some(turn) {
1594 history.push(Message::User(
1595 "[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(),
1596 ));
1597 }
1598 report.turn_usage.last_mut().unwrap().tools_ms =
1599 now().saturating_duration_since(tools_start).as_millis() as u64;
1600 continue;
1601 }
1602
1603 last_turn_called_tools = false;
1605 if report.gate_attempts > 0
1606 && CLAIM_PHRASES
1607 .iter()
1608 .any(|&p| resp.text.to_lowercase().contains(p))
1609 {
1610 if let (Some(last_fp), Some(curr_fp), Some(base_commit)) =
1611 (&last_fingerprint, self.fingerprint(), &baseline)
1612 {
1613 if *last_fp == curr_fp && self.check_blocked_at_base(base_commit, &last_failed)
1614 {
1615 let steps = last_failed.join("; ");
1616 let text: String = resp.text.chars().take(300).collect();
1617 return (
1618 Outcome::Blocked(format!(
1619 "the check fails at the base commit too ({steps}); the model said: {text}"
1620 )),
1621 report,
1622 );
1623 }
1624 }
1625 }
1626
1627 if state.brief.verification_cmd.trim().is_empty() {
1628 if state.brief.instructions.is_some() {
1629 return (Outcome::Finished, report);
1630 }
1631 self.finalize_polled_base_check(&mut report);
1632 return (Outcome::Verified, report);
1633 }
1634
1635 progressed = true;
1636 report.gate_attempts += 1;
1637 report.gate_turns.push(turn);
1638 self.emit(Event::GateStart {
1639 attempt: report.gate_attempts,
1640 });
1641 let gate_start = now();
1642 let (mut passed, mut output, wait_ms, failing) =
1643 self.run_gate(state, &last_failed, &mut deadline, now);
1644 last_failed = failing;
1645 if passed && self.research {
1646 let mut problems = self.check_report_quotes(seen_names);
1647 if !problems.is_empty() {
1648 passed = false;
1649 output = format!("exit 1\n{}", research_check::render(&problems));
1650 }
1651 problems.truncate(research_check::MAX_PROBLEMS);
1652 report.quote_problems = Some(problems);
1653 if passed {
1654 if let Some(cc) = self.run_claim_check(redactor, claim_deadline, now) {
1655 report.usage.input += cc.usage.input;
1656 report.usage.cached += cc.usage.cached;
1657 report.usage.output += cc.usage.output;
1658 report.usage.thinking += cc.usage.thinking;
1659 report.claim_check_skipped = cc.skipped.clone();
1660 if !cc.contradicted.is_empty() && !claim_round_done {
1661 claim_round_done = true;
1662 passed = false;
1663 let mut lines: Vec<String> = cc
1664 .contradicted
1665 .iter()
1666 .map(|f| {
1667 let text: String = f.text.chars().take(200).collect();
1668 format!("report.md:{}: {text}\n checker: {}", f.line, f.reason)
1669 })
1670 .collect();
1671 lines.push(
1672 "These claims do not match the lines they cite. Fix each claim, cite the lines that support it, or remove it."
1673 .to_string(),
1674 );
1675 output = format!("exit 1\n{}", lines.join("\n"));
1676 }
1677 if cc.calls > 0 || cc.skipped.is_none() {
1678 report.claim_check = Some(cc);
1679 }
1680 }
1681 }
1682 }
1683 report
1684 .gate_ms
1685 .push(now().saturating_duration_since(gate_start).as_millis() as u64);
1686 report.gate_wait_ms.push(wait_ms);
1687 self.emit(Event::Gate {
1688 attempt: report.gate_attempts,
1689 passed,
1690 output: output.lines().next().unwrap_or(""),
1691 });
1692 if passed {
1693 self.finalize_polled_base_check(&mut report);
1694 return (Outcome::Verified, report);
1695 }
1696 report.gate_failures.push(cut_gate_output(&output));
1697 if deadline.is_some_and(|d| now() >= d) {
1698 return (Outcome::BudgetExhausted, report);
1699 }
1700
1701 last_fingerprint = self.fingerprint();
1702 if last_fingerprint != start_fp {
1703 progressed = true;
1704 }
1705
1706 if self.rollback {
1707 if let Some(base) = &baseline {
1708 if let Err(msg) = self.reset_to(base) {
1709 return (Outcome::Error(msg), report);
1710 }
1711 state.runtime.rollbacks += 1;
1712 let short_sha = &base[..base.len().min(8)];
1713 self.emit(Event::RolledBack { to: short_sha });
1714 }
1715 }
1716 if report.gate_attempts >= self.budget.max_gate_attempts {
1717 return (Outcome::GateFailed, report);
1718 }
1719
1720 let reset_note = if self.rollback && baseline.is_some() {
1724 "\n\nYour changes have been reverted to the last verified state. Start from \
1725 the current files, not from what you remember writing."
1726 } else {
1727 ""
1728 };
1729 let advice = if self.research {
1730 "Fix report.md as listed above, then reply with one line."
1731 } else {
1732 "If the failure is caused by your change, fix your change, not the machine. \
1733 If it is not caused by your change (disk space, network, a missing service), \
1734 say so and stop."
1735 };
1736 history.push(Message::User(format!(
1737 "Verification did not pass.\n\n{output}\n\n{advice}{reset_note}"
1738 )));
1739 }
1740 (Outcome::BudgetExhausted, report)
1741 }
1742
1743 fn finalize_polled_base_check(&self, report: &mut RunReport) {
1744 let BaseCheck::Polled(handle) = self.base_check else {
1745 return;
1746 };
1747 if report.base_check_passed == Some(true) {
1748 if report.base_check_seconds.is_none() {
1749 report.base_check_seconds = handle.elapsed_seconds();
1750 }
1751 return;
1752 }
1753 let final_state = match handle.poll() {
1754 BaseCheckState::Pending => handle.wait(),
1755 other => other,
1756 };
1757 report.base_check_seconds = handle.elapsed_seconds();
1758 match final_state {
1759 BaseCheckState::Passed => {
1760 report.base_check_passed = Some(true);
1761 }
1762 BaseCheckState::Failed { .. } => {
1763 report.base_check_passed = Some(false);
1764 let note = "the check failed on the untouched code but passes with this change";
1765 report.final_message = Some(match report.final_message.take() {
1766 Some(existing) if !existing.is_empty() => format!("{existing}\n\n{note}"),
1767 _ => note.to_string(),
1768 });
1769 }
1770 BaseCheckState::Pending => {}
1771 }
1772 }
1773}
1774
1775const 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.";
1777
1778pub fn sandbox_denial_hint(output: &str) -> Option<&'static str> {
1780 if output
1781 .to_ascii_lowercase()
1782 .contains("operation not permitted")
1783 {
1784 Some(SANDBOX_DENIAL_HINT)
1785 } else {
1786 None
1787 }
1788}
1789
1790fn append_hint_line(output: &mut String, hint: &str) {
1791 if output.trim_end_matches(['\r', '\n']).ends_with(hint) {
1792 return;
1793 }
1794 if !output.ends_with('\n') {
1795 output.push('\n');
1796 }
1797 output.push_str(hint);
1798}
1799
1800fn attach_sandbox_denial_hint(result: &mut GateRunResult) {
1801 if result.passed {
1802 return;
1803 }
1804 let hint = sandbox_denial_hint(&result.output).or_else(|| {
1805 result
1806 .failures
1807 .iter()
1808 .find_map(|f| sandbox_denial_hint(&f.output))
1809 });
1810 let Some(hint) = hint else {
1811 return;
1812 };
1813 append_hint_line(&mut result.output, hint);
1814 if let Some(last) = result.failures.last_mut() {
1815 append_hint_line(&mut last.output, hint);
1816 }
1817}
1818
1819#[derive(Debug, Clone, PartialEq, Eq)]
1820pub struct GateStepFailure {
1821 pub step: String,
1822 pub output: String,
1823}
1824
1825#[derive(Debug, Clone, PartialEq, Eq)]
1827pub struct GateRunResult {
1828 pub passed: bool,
1829 pub output: String,
1830 pub wait_ms: u64,
1831 pub failures: Vec<GateStepFailure>,
1832}
1833
1834pub fn run_gate_step(
1836 shell: &dyn Shell,
1837 cmd: &str,
1838 dir: &Path,
1839 deadline: Option<std::time::Instant>,
1840 now: &(dyn Fn() -> std::time::Instant + Sync),
1841) -> (bool, String) {
1842 let timeout = match deadline {
1843 Some(d) => {
1844 let left = d.saturating_duration_since(now());
1845 if left.is_zero() {
1846 return (false, "exit 124\ngate ran out of time".into());
1847 }
1848 Duration::from_secs(1800).min(left)
1849 }
1850 None => Duration::from_secs(1800),
1851 };
1852 let wrapped = format!("(export {}=1\n{cmd}\n)", gate_slots::IN_GATE_ENV);
1853 let (passed, output) = match shell.exec(&wrapped, dir, timeout) {
1854 Ok(o) => {
1855 let merged = o.merged();
1856 let raw = merged.trim_end();
1857 let body = tools::bound_output(raw);
1858 let dropped: Vec<&str> = if o.exit_code != 0 {
1859 let kept: std::collections::HashSet<&str> = body.lines().map(str::trim).collect();
1860 summary_lines(raw)
1861 .into_iter()
1862 .filter(|l| !kept.contains(l))
1863 .collect()
1864 } else {
1865 Vec::new()
1866 };
1867 let content = if dropped.is_empty() {
1868 body
1869 } else {
1870 let block = format!("Failing, in lines blyte left out:\n{}", dropped.join("\n"));
1871 if body.is_empty() {
1872 block
1873 } else {
1874 format!("{block}\n\n{body}")
1875 }
1876 };
1877 if o.exit_code != 0 && deadline.is_some_and(|d| now() >= d) {
1878 let text = if content.is_empty() {
1879 format!("exit {}\ngate ran out of time", o.exit_code)
1880 } else {
1881 format!("exit {}\ngate ran out of time\n{content}", o.exit_code)
1882 };
1883 (false, text)
1884 } else {
1885 (o.exit_code == 0, format!("exit {}\n{content}", o.exit_code))
1886 }
1887 }
1888 Err(e) => {
1889 let text = if deadline.is_some_and(|d| now() >= d) {
1890 format!("gate ran out of time: {e}")
1891 } else {
1892 format!("verification command could not run: {e}")
1893 };
1894 (false, text)
1895 }
1896 };
1897 match crate::redact::Redactor::for_root(dir) {
1898 Ok(redactor) => (passed, redactor.apply(&output)),
1899 Err(e) => (false, e),
1900 }
1901}
1902
1903pub fn run_gate_steps(
1905 shell: &dyn Shell,
1906 gate: &str,
1907 dir: &Path,
1908 last_failed: &[String],
1909 deadline: &mut Option<std::time::Instant>,
1910 on_slot_wait: impl FnOnce(u64),
1911 now: &(dyn Fn() -> std::time::Instant + Sync),
1912) -> GateRunResult {
1913 run_gate_steps_cancellable(
1914 shell,
1915 gate,
1916 dir,
1917 last_failed,
1918 deadline,
1919 on_slot_wait,
1920 now,
1921 None,
1922 )
1923}
1924
1925#[allow(clippy::too_many_arguments)]
1927pub fn run_gate_steps_cancellable(
1928 shell: &dyn Shell,
1929 gate: &str,
1930 dir: &Path,
1931 last_failed: &[String],
1932 deadline: &mut Option<std::time::Instant>,
1933 on_slot_wait: impl FnOnce(u64),
1934 now: &(dyn Fn() -> std::time::Instant + Sync),
1935 cancel: Option<&crate::shell::CancelHandle>,
1936) -> GateRunResult {
1937 let (_guard, wait_ms) = if gate_slots::enabled() && !gate_slots::nested() {
1938 let max_slots = gate_slots::slots();
1939 let slot_dir = gate_slots::slot_dir();
1940 match gate_slots::acquire_cancellable(
1941 max_slots,
1942 &slot_dir,
1943 Duration::from_millis(500),
1944 cancel.map(crate::shell::CancelHandle::flag),
1945 ) {
1946 Ok(Some((guard, waited))) => {
1947 let wait_ms = waited.as_millis() as u64;
1948 if let Some(d) = deadline.as_mut() {
1949 *d += waited;
1950 }
1951 if wait_ms > 0 {
1952 eprintln!(
1953 "gate: waited {}s for a gate slot ({max_slots} in use)",
1954 waited.as_secs()
1955 );
1956 on_slot_wait(wait_ms);
1957 }
1958 (Some(guard), wait_ms)
1959 }
1960 Ok(None) => {
1961 return GateRunResult {
1962 passed: false,
1963 output: "cancelled".into(),
1964 wait_ms: 0,
1965 failures: Vec::new(),
1966 };
1967 }
1968 Err(e) => {
1969 eprintln!("gate: slot acquisition failed: {e}");
1970 (None, 0)
1971 }
1972 }
1973 } else {
1974 (None, 0)
1975 };
1976
1977 if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
1978 return GateRunResult {
1979 passed: false,
1980 output: "cancelled".into(),
1981 wait_ms,
1982 failures: Vec::new(),
1983 };
1984 }
1985
1986 let steps = gate_steps(gate);
1987 if steps.len() <= 1 {
1988 let step_cmd = steps.first().copied().unwrap_or(gate);
1989 let (passed, output) = run_gate_step(shell, step_cmd, dir, *deadline, now);
1990 let failures = if passed {
1991 Vec::new()
1992 } else {
1993 vec![GateStepFailure {
1994 step: step_cmd.to_string(),
1995 output: output.clone(),
1996 }]
1997 };
1998 let mut result = GateRunResult {
1999 passed,
2000 output,
2001 wait_ms,
2002 failures,
2003 };
2004 attach_sandbox_denial_hint(&mut result);
2005 return result;
2006 }
2007 let (first_group, second_group) = {
2008 let (f, s) = retry_order(&steps, last_failed);
2009 if f.is_empty() {
2010 (steps.clone(), Vec::new())
2011 } else {
2012 (f, s)
2013 }
2014 };
2015 let mut formatted_failures = Vec::new();
2016 let mut failures = Vec::new();
2017 for &step in &first_group {
2018 if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
2019 break;
2020 }
2021 let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
2022 if !passed {
2023 formatted_failures.push(format!("$ {step}\n{output}"));
2024 failures.push(GateStepFailure {
2025 step: step.to_string(),
2026 output,
2027 });
2028 if deadline.is_some_and(|d| now() >= d)
2029 || cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
2030 {
2031 break;
2032 }
2033 }
2034 }
2035 if !failures.is_empty() {
2036 let body = tools::bound_output(&formatted_failures.join("\n\n"));
2037 let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
2038 let not_rerun = if !second_group.is_empty() {
2039 format!(
2040 "\nNot re-run this attempt: {} step(s) that passed last time ({}).",
2041 second_group.len(),
2042 second_group.join(", ")
2043 )
2044 } else {
2045 String::new()
2046 };
2047 let mut result = GateRunResult {
2048 passed: false,
2049 output: format!(
2050 "{} of {} steps failed: {}{not_rerun}\n\n{body}",
2051 failures.len(),
2052 steps.len(),
2053 failed_names.join(", ")
2054 ),
2055 wait_ms,
2056 failures,
2057 };
2058 attach_sandbox_denial_hint(&mut result);
2059 return result;
2060 }
2061 for &step in &second_group {
2062 if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
2063 break;
2064 }
2065 let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
2066 if !passed {
2067 formatted_failures.push(format!("$ {step}\n{output}"));
2068 failures.push(GateStepFailure {
2069 step: step.to_string(),
2070 output,
2071 });
2072 if deadline.is_some_and(|d| now() >= d)
2073 || cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
2074 {
2075 break;
2076 }
2077 }
2078 }
2079 if failures.is_empty() {
2080 return GateRunResult {
2081 passed: true,
2082 output: "exit 0".into(),
2083 wait_ms,
2084 failures: Vec::new(),
2085 };
2086 }
2087 let body = tools::bound_output(&formatted_failures.join("\n\n"));
2088 let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
2089 let mut result = GateRunResult {
2090 passed: false,
2091 output: format!(
2092 "{} of {} steps failed: {}\n\n{body}",
2093 failures.len(),
2094 steps.len(),
2095 failed_names.join(", ")
2096 ),
2097 wait_ms,
2098 failures,
2099 };
2100 attach_sandbox_denial_hint(&mut result);
2101 result
2102}
2103
2104pub fn gate_steps(gate: &str) -> Vec<&str> {
2106 gate.lines()
2107 .map(str::trim)
2108 .filter(|s| !s.is_empty())
2109 .collect()
2110}
2111
2112pub fn retry_order<'a>(steps: &[&'a str], last_failed: &[String]) -> (Vec<&'a str>, Vec<&'a str>) {
2115 if last_failed.is_empty() {
2116 return (steps.to_vec(), Vec::new());
2117 }
2118 let mut failed = Vec::new();
2119 let mut others = Vec::new();
2120 for &step in steps {
2121 if last_failed.iter().any(|f| f == step) {
2122 failed.push(step);
2123 } else {
2124 others.push(step);
2125 }
2126 }
2127 (failed, others)
2128}
2129
2130fn is_summary_line(line: &str) -> bool {
2132 let t = line.trim();
2133 ((t.starts_with("FAILED ") || t.starts_with("ERROR "))
2134 && (t.contains("::") || t.contains(".py")))
2135 || (t.starts_with('=') && (t.contains(" failed") || t.contains(" error")))
2136 || (t.starts_with("test ") && t.ends_with("FAILED"))
2137 || t.starts_with("error[")
2138 || t.starts_with("error:")
2139 || t.starts_with("test result: FAILED")
2140}
2141
2142fn summary_lines(output: &str) -> Vec<&str> {
2144 let mut lines = Vec::new();
2145 let mut seen = std::collections::HashSet::new();
2146 for line in output.lines() {
2147 let t = line.trim();
2148 if is_summary_line(t) && seen.insert(t) {
2149 lines.push(t);
2150 if lines.len() == 40 {
2151 break;
2152 }
2153 }
2154 }
2155 lines
2156}
2157
2158fn is_blyte_header(line: &str) -> bool {
2160 let t = line.trim();
2161 let Some((n, rest)) = t.split_once(" of ") else {
2162 return false;
2163 };
2164 if !n.chars().all(|c| c.is_ascii_digit()) || n.is_empty() {
2165 return false;
2166 }
2167 let Some((m, _)) = rest.split_once(" steps failed:") else {
2168 return false;
2169 };
2170 m.chars().all(|c| c.is_ascii_digit()) && !m.is_empty()
2171}
2172
2173pub fn cut_gate_output(output: &str) -> String {
2176 const MAX_CHARS: usize = 4_000;
2177
2178 let total_chars = output.chars().count();
2179 if total_chars <= MAX_CHARS {
2180 return output.to_string();
2181 }
2182
2183 let sum_lines = summary_lines(output);
2184 let has_summary = !sum_lines.is_empty();
2185
2186 let first_line = output.lines().next().unwrap_or("");
2187 let has_blyte_header = is_blyte_header(first_line);
2188
2189 let (header, rem) = if has_summary && has_blyte_header {
2190 let rem = &output[first_line.len()..];
2191 let rem = rem.trim_start_matches(['\r', '\n']);
2192 (Some(first_line), rem)
2193 } else {
2194 (None, output)
2195 };
2196
2197 let summary_block = if has_summary {
2198 let mut block = String::from("Failing, from the full output:\n");
2199 block.push_str(&sum_lines.join("\n"));
2200 Some(block)
2201 } else {
2202 None
2203 };
2204
2205 let prefix_chars = header.map(|h| h.chars().count() + 1).unwrap_or(0)
2206 + summary_block
2207 .as_ref()
2208 .map(|s| s.chars().count() + 1)
2209 .unwrap_or(0);
2210
2211 let available = MAX_CHARS.saturating_sub(prefix_chars);
2212 let head_budget = available / 4;
2213 let tail_budget = available - head_budget;
2214
2215 let head = if head_budget == 0 || rem.is_empty() {
2216 ""
2217 } else {
2218 let head_cand_end = rem
2219 .char_indices()
2220 .nth(head_budget)
2221 .map(|(i, _)| i)
2222 .unwrap_or(rem.len());
2223 let head_cand = &rem[..head_cand_end];
2224 match head_cand.rfind('\n') {
2225 Some(idx) => &head_cand[..idx],
2226 None => head_cand,
2227 }
2228 };
2229
2230 let tail = if tail_budget == 0 {
2231 ""
2232 } else {
2233 let tail_cand_start = output
2234 .char_indices()
2235 .nth(total_chars.saturating_sub(tail_budget))
2236 .map(|(i, _)| i)
2237 .unwrap_or(output.len());
2238 let tail_cand = &output[tail_cand_start..];
2239 match tail_cand.find('\n') {
2240 Some(idx) => &tail_cand[idx + 1..],
2241 None => tail_cand,
2242 }
2243 };
2244
2245 let dropped = total_chars.saturating_sub(head.chars().count() + tail.chars().count());
2246
2247 let mut pieces = Vec::new();
2248 if let Some(h) = header {
2249 pieces.push(h);
2250 }
2251 if let Some(sb) = &summary_block {
2252 pieces.push(sb.as_str());
2253 }
2254 if !head.is_empty() {
2255 pieces.push(head);
2256 }
2257 let marker = format!("… [{dropped} characters cut] …");
2258 pieces.push(&marker);
2259 if !tail.is_empty() {
2260 pieces.push(tail);
2261 }
2262 let mut joined = pieces.join("\n");
2263 if output
2264 .trim_end_matches(['\r', '\n'])
2265 .ends_with(SANDBOX_DENIAL_HINT)
2266 {
2267 append_hint_line(&mut joined, SANDBOX_DENIAL_HINT);
2268 }
2269 joined
2270}
2271
2272fn format_blyte_arg(arg: &str) -> String {
2273 if arg.is_empty()
2274 || arg
2275 .chars()
2276 .any(|c| c.is_whitespace() || c == '"' || c == '\'')
2277 {
2278 serde_json::to_string(arg).unwrap_or_else(|_| format!("\"{arg}\""))
2279 } else {
2280 arg.to_string()
2281 }
2282}
2283
2284pub fn format_blyte_tool_input(args: &serde_json::Value) -> Option<String> {
2285 let raw_args = args.get("args")?.as_array()?;
2286 let mut parts = Vec::with_capacity(raw_args.len() + 1);
2287 parts.push("blyte".to_string());
2288 for item in raw_args {
2289 parts.push(format_blyte_arg(item.as_str()?));
2290 }
2291 let mut cmd = parts.join(" ");
2292 if args.get("background").and_then(|v| v.as_bool()) == Some(true) {
2293 cmd.push_str(" (background)");
2294 }
2295 Some(cmd)
2296}
2297
2298pub fn extract_action_target(tool: &str, args: &serde_json::Value) -> String {
2310 match tool {
2312 "read" => {
2313 if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2315 let start = args.get("start_line").and_then(|v| {
2316 v.as_u64()
2317 .map(|n| n.to_string())
2318 .or_else(|| v.as_str().map(|s| s.to_string()))
2319 });
2320 let end = args.get("end_line").and_then(|v| {
2321 v.as_u64()
2322 .map(|n| n.to_string())
2323 .or_else(|| v.as_str().map(|s| s.to_string()))
2324 });
2325 match (start, end) {
2327 (Some(s), Some(e)) => return format!("{path} (L{s}-L{e})"),
2328 (Some(s), None) => return format!("{path} (L{s}+)"),
2329 (None, Some(e)) => return format!("{path} (L1-L{e})"),
2330 (None, None) => return path.to_string(),
2331 }
2332 }
2333 }
2334 "write" => {
2335 if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2337 if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
2338 return format!("{path} ({} bytes)", content.len());
2339 }
2340 return path.to_string();
2341 }
2342 }
2343 "edit" => {
2344 if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2346 return path.to_string();
2347 }
2348 }
2349 "bash" => {
2350 if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
2353 let single_line = cmd.replace('\n', " ");
2354 if single_line.chars().count() > 60 {
2355 let prefix: String = single_line.chars().take(57).collect();
2356 return format!("{prefix}...");
2357 }
2358 return single_line;
2359 }
2360 }
2361 "glob" => {
2362 if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
2364 return pattern.to_string();
2365 }
2366 }
2367 "grep" => {
2368 if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
2370 if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2371 if !path.is_empty() {
2372 return format!("pattern '{pattern}' in {path}");
2373 }
2374 }
2375 return format!("pattern '{pattern}'");
2376 }
2377 }
2378 "blyte" => {
2379 if let Some(cmd) = format_blyte_tool_input(args) {
2380 return cmd;
2381 }
2382 }
2383 _ => {}
2384 }
2385
2386 if let Some(obj) = args.as_object() {
2388 for val in obj.values() {
2389 if let Some(s) = val.as_str() {
2390 return s.to_string();
2391 }
2392 }
2393 }
2394 tool.to_string()
2395}
2396
2397pub fn extract_action_summary(tool: &str, content: &str, is_error: bool) -> String {
2407 match tool {
2409 "read" => {
2410 if is_error {
2411 let first = content
2412 .lines()
2413 .find(|l| !l.trim().is_empty())
2414 .unwrap_or("read failed");
2415 let clamped: String = first.chars().take(80).collect();
2416 format!("failed: {clamped}")
2417 } else {
2418 let count = content.lines().count();
2420 format!("{count} lines read")
2421 }
2422 }
2423 "write" => {
2424 if is_error {
2425 let first = content
2426 .lines()
2427 .find(|l| !l.trim().is_empty())
2428 .unwrap_or("write failed");
2429 let clamped: String = first.chars().take(80).collect();
2430 format!("failed: {clamped}")
2431 } else {
2432 "file written".to_string()
2434 }
2435 }
2436 "edit" => {
2437 if is_error {
2439 let first = content
2440 .lines()
2441 .find(|l| !l.trim().is_empty())
2442 .unwrap_or("edit failed");
2443 let clamped: String = first.chars().take(80).collect();
2444 format!("failed: {clamped}")
2445 } else {
2446 "string replaced".to_string()
2447 }
2448 }
2449 "bash" => {
2450 if !is_error {
2452 "exit 0".to_string()
2453 } else {
2454 let last_line = content
2455 .lines()
2456 .rev()
2457 .find(|l| !l.trim().is_empty())
2458 .unwrap_or("command failed");
2459 let clamped: String = last_line.chars().take(80).collect();
2460 format!("failed: {clamped}")
2461 }
2462 }
2463 "glob" => {
2464 if is_error {
2465 let first = content
2466 .lines()
2467 .find(|l| !l.trim().is_empty())
2468 .unwrap_or("glob failed");
2469 let clamped: String = first.chars().take(80).collect();
2470 format!("failed: {clamped}")
2471 } else {
2472 let count = content.lines().filter(|l| !l.trim().is_empty()).count();
2474 format!("{count} files matched")
2475 }
2476 }
2477 "grep" => {
2478 if is_error {
2479 let first = content
2480 .lines()
2481 .find(|l| !l.trim().is_empty())
2482 .unwrap_or("grep failed");
2483 let clamped: String = first.chars().take(80).collect();
2484 format!("failed: {clamped}")
2485 } else {
2486 let count = content.lines().filter(|l| !l.trim().is_empty()).count();
2488 format!("{count} matches found")
2489 }
2490 }
2491 _ => {
2492 let first = content.lines().next().unwrap_or("");
2494 first.chars().take(80).collect()
2495 }
2496 }
2497}