1use crate::approval::ApprovalGate;
25use crate::config::EgressMode;
26use crate::config::{AgentsConfig, CompactionMode, LimitsConfig};
27use crate::guardrails::Guardrails;
28use crate::limits::LimitKind;
29use crate::memory::sizing::{
30 aged_view, calibrated_budget, result_cap, shorten_middle, sized_reserve,
31};
32use crate::memory::working::{
33 apply_progress, apply_summary, compacted_notice, compaction_failed_notice, compaction_plan,
34 count_spec_tokens, count_tokens, fit_pinned, fits, python_strip, summary_request_text,
35 trimmed_notice, Cut, Fitted, KEEP_RECENT, SUMMARY_MAX_TOKENS, SUMMARY_RETRY_NOTE,
36 SUMMARY_SYSTEM_PROMPT,
37};
38use crate::observability::Recorder;
39use crate::prompt::{time_note, with_turn_note, without_turn_note};
40use crate::provider::reasoning::REASONING_LOOP;
41use crate::provider::{Provider, ProviderError};
42use crate::pyjson::{python_float_repr, python_json_dumps};
43use crate::router::Router;
44use crate::session::{AgentState, OpenTurn};
45use crate::tools::{ToolContext, ToolRegistry};
46use crate::turn::TurnSummary;
47use crate::types::{
48 python_repr, AgentPhase, CompletionRequest, Message, Role, Step, ToolCall, ToolResult,
49 ToolSpec, Usage,
50};
51use crate::vault::StreamRedactor;
52use futures_util::StreamExt;
53use serde_json::{json, Value};
54use std::collections::HashMap;
55use std::sync::atomic::{AtomicBool, Ordering};
56use std::sync::Arc;
57use std::time::{Duration, Instant};
58use thiserror::Error;
59
60pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
62
63pub const MAX_CONTINUATIONS: u64 = 3;
65
66const SUMMARY_MARGIN_TOKENS: u64 = 256;
69
70const MIN_TRANSCRIPT_TOKENS: u64 = 1_024;
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum SummaryError {
76 Cancelled,
77 Failed(String),
79 Empty,
81}
82
83#[derive(Debug, Clone)]
85pub(crate) struct WrittenSummary {
86 pub outcome: Result<String, SummaryError>,
87 pub usage: Usage,
88 pub model: String,
89}
90
91struct Compaction {
93 notice: String,
94 summary: Option<String>,
95}
96
97struct TurnWindow<'g> {
100 goal_text: &'g str,
102 goal: usize,
104 continuation: Option<usize>,
106 retry_at: Option<u64>,
108 trim_announced: bool,
110 trimmed: usize,
112 aged: usize,
114}
115
116pub fn continuation_notice(index: u64) -> String {
118 format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
119}
120
121pub const ANSWER_PROMPT: &str =
123 "Your last reply was empty. Give the user your answer now, as plain text.";
124
125pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
127
128pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
130
131pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
133
134pub const REASONING_LOOP_NOTICE: &str =
137 "\n[the model's reasoning was repeating itself; stopped it]\n";
138
139pub fn ollama_loop_hint(model: &str) -> String {
145 format!(
146 "[if Ollama keeps doing this, its runner may be stuck: \
147 `ollama stop {model}` unloads the model, and the next request loads it fresh]\n"
148 )
149}
150
151pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
153
154pub const CONTINUED_NOTE: &str = "This turn stopped before it finished and is now continuing \
160 at the user's request. Time has passed: files and anything else your earlier tool calls \
161 looked at may have changed, and calls made just before the stop may have run without \
162 their results being recorded. Check the current state before relying on earlier results.";
163
164pub const UNRECORDED_RESULT: &str =
168 "No result was recorded: the turn stopped before it was. The call may have run.";
169
170pub fn continued_notice(steps: u32) -> String {
172 format!("[continuing the turn after step {steps}]\n")
173}
174
175#[derive(Debug, Clone, PartialEq, Eq, Error)]
178#[error("{0}")]
179pub struct NotContinuable(pub String);
180
181#[derive(Debug, Clone)]
184pub struct Continuation {
185 open: OpenTurn,
186 goal_text: String,
187 skill: Option<Arc<crate::skills::Skill>>,
188}
189
190impl PartialEq for Continuation {
193 fn eq(&self, other: &Self) -> bool {
194 self.open == other.open
195 && self.goal_text == other.goal_text
196 && self.skill.as_ref().map(|skill| &skill.name)
197 == other.skill.as_ref().map(|skill| &skill.name)
198 }
199}
200
201impl Eq for Continuation {}
202
203impl Continuation {
204 pub fn steps(&self) -> u32 {
206 self.open.steps
207 }
208
209 pub fn cost_usd(&self) -> f64 {
211 self.open.cost_usd
212 }
213}
214
215#[derive(Clone, Copy)]
217enum Start<'a> {
218 New(&'a str),
219 Continue(&'a Continuation),
220}
221
222#[derive(Clone, Default)]
227pub struct CancelToken {
228 inner: Arc<CancelInner>,
229}
230
231impl std::fmt::Debug for CancelToken {
232 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 formatter
234 .debug_struct("CancelToken")
235 .field("cancelled", &self.is_cancelled())
236 .finish()
237 }
238}
239
240#[derive(Default)]
241struct CancelInner {
242 flag: AtomicBool,
243 notify: tokio::sync::Notify,
244}
245
246impl CancelToken {
247 pub fn cancel(&self) {
248 self.inner.flag.store(true, Ordering::SeqCst);
249 self.inner.notify.notify_waiters();
250 }
251
252 pub fn is_cancelled(&self) -> bool {
253 self.inner.flag.load(Ordering::SeqCst)
254 }
255
256 pub fn clear(&self) {
257 self.inner.flag.store(false, Ordering::SeqCst);
258 }
259
260 pub async fn cancelled(&self) {
262 loop {
263 let notified = self.inner.notify.notified();
264 tokio::pin!(notified);
265 notified.as_mut().enable();
267 if self.is_cancelled() {
268 return;
269 }
270 notified.await;
271 }
272 }
273}
274
275#[derive(Debug, Clone, Copy)]
282#[non_exhaustive]
283pub enum TurnEvent<'a> {
284 Text(&'a str),
286 Notice(&'a str),
290 Thinking(&'a str),
293 ToolCall { call: &'a ToolCall, text: &'a str },
295 ToolResult {
298 call: &'a ToolCall,
299 result: &'a ToolResult,
300 observation: &'a str,
301 text: &'a str,
302 },
303 Usage {
307 step: &'a crate::types::Usage,
308 session: &'a crate::types::Usage,
309 },
310 Compacted {
315 notice: &'a str,
316 summary: Option<&'a str>,
317 },
318 #[cfg(feature = "agent86ui")]
322 Ui(&'a agent86_ui::AgentMessage),
323}
324
325impl<'a> TurnEvent<'a> {
326 pub fn text(&self) -> &'a str {
328 match *self {
329 Self::Text(text)
330 | Self::Notice(text)
331 | Self::ToolCall { text, .. }
332 | Self::ToolResult { text, .. }
333 | Self::Compacted { notice: text, .. } => text,
334 Self::Thinking(_) | Self::Usage { .. } => "",
335 #[cfg(feature = "agent86ui")]
336 Self::Ui(_) => "",
337 }
338 }
339}
340
341#[derive(Debug, Clone, PartialEq, Error)]
343pub enum HarnessError {
344 #[error(transparent)]
345 Provider(#[from] ProviderError),
346
347 #[error("Circuit tripped: {0}")]
348 CircuitTripped(String),
349
350 #[error(
351 "The '{provider}' provider ended its stream for model {} without a final completion. \
352 The response was truncated; retry, or check the endpoint's streaming implementation.",
353 python_repr(model)
354 )]
355 NoFinalCompletion { provider: String, model: String },
356}
357
358impl HarnessError {
359 pub fn python_type(&self) -> &'static str {
362 match self {
363 Self::Provider(_) => "ProviderError",
364 Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
365 }
366 }
367}
368
369pub struct CircuitBreaker {
371 limits: LimitsConfig,
372 steps: u32,
373 cost_usd: f64,
374 consecutive_errors: u32,
375 started: Instant,
376}
377
378impl CircuitBreaker {
379 pub fn new(limits: &LimitsConfig) -> Self {
380 Self {
381 limits: limits.clone(),
382 steps: 0,
383 cost_usd: 0.0,
384 consecutive_errors: 0,
385 started: Instant::now(),
386 }
387 }
388
389 pub fn steps(&self) -> u32 {
390 self.steps
391 }
392
393 fn carry_over(&mut self, open: &OpenTurn) {
397 self.steps = open.steps;
398 self.cost_usd = open.cost_usd;
399 self.consecutive_errors = open.consecutive_errors;
400 }
401
402 pub fn max_steps(&self) -> u32 {
404 self.limits.max_steps
405 }
406
407 pub fn set_max_steps(&mut self, max_steps: u32) {
409 self.limits.max_steps = max_steps;
410 }
411
412 pub fn out_of_steps(&self) -> bool {
414 self.steps >= self.limits.max_steps
415 }
416
417 pub fn before_step(&self) -> Result<(), HarnessError> {
419 let limits = &self.limits;
420 if self.steps >= limits.max_steps {
421 return Err(trip(format!(
422 "step budget reached ({} steps)",
423 limits.max_steps
424 )));
425 }
426 if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
427 return Err(trip(format!(
428 "cost cap reached (${:.4} >= ${})",
429 self.cost_usd,
430 python_float_repr(limits.max_cost_usd)
431 )));
432 }
433 let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
434 if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
435 return Err(trip(format!(
436 "wall-clock limit reached ({}s)",
437 limits.max_wall_clock_s
438 )));
439 }
440 Ok(())
441 }
442
443 pub fn record_step(&mut self, usage: &Usage) {
444 self.steps += 1;
445 self.cost_usd += usage.cost_usd;
446 }
447
448 pub fn cost(&self) -> f64 {
451 self.cost_usd
452 }
453
454 pub fn record_cost(&mut self, cost_usd: f64) {
455 self.cost_usd += cost_usd;
456 }
457
458 pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
459 if ok {
460 self.consecutive_errors = 0;
461 return Ok(());
462 }
463 self.consecutive_errors += 1;
464 if self.consecutive_errors > self.limits.max_consecutive_errors {
465 return Err(trip(format!(
466 "aborted after {} consecutive tool errors",
467 self.consecutive_errors
468 )));
469 }
470 Ok(())
471 }
472}
473
474fn trip(reason: String) -> HarnessError {
475 HarnessError::CircuitTripped(reason)
476}
477
478pub struct Harness {
480 pub provider: Arc<dyn Provider>,
483 pub router: Router,
485 pub tracer: crate::otel::Tracer,
487 pub registry: ToolRegistry,
488 pub context: ToolContext,
489 pub limits: LimitsConfig,
490 pub agents: AgentsConfig,
492 pub system: Message,
493 pub max_tokens: u32,
496 pub session_limits: crate::limits::SessionLimits,
499 pub context_window: u64,
502 pub gate: ApprovalGate,
504 pub guardrails: Guardrails,
506 pub recorder: Recorder,
508 pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
511 pub memory: Option<crate::session::SessionStore>,
514 pub cancel: CancelToken,
516 pub subagents: crate::subagent::SubagentState,
519 pub calibration: crate::memory::sizing::Calibration,
522 pub verify: crate::verify::Verify,
524}
525
526impl Harness {
527 pub(crate) fn system_message(&self) -> Message {
534 let offered = self.delegation_offered(&self.context, 0);
535 if let Some((persona, preloaded, _, _)) = self.subagents.main() {
537 return self.filtered_system(&persona, &self.context, &preloaded, offered, None);
538 }
539 self.system_for(&self.context, offered, None)
540 }
541
542 pub(crate) fn system_for(
546 &self,
547 ctx: &ToolContext,
548 delegation_offered: bool,
549 extra: Option<&str>,
550 ) -> Message {
551 let mut system = self.system.clone();
552 if let Some(section) = self
553 .mcp
554 .as_ref()
555 .map(|mcp| mcp.prompt_section())
556 .filter(|section| !section.is_empty())
557 {
558 system.content = format!("{}\n\n{section}", system.content);
559 }
560 if delegation_offered {
561 if let Some(section) = self.specialty_listing(ctx) {
562 system.content = format!("{}\n\n{section}", system.content);
563 }
564 }
565 if let Some(section) = ctx.secrets.prompt_section() {
566 system.content = format!("{}\n\n{section}", system.content);
567 }
568 if crate::ask::reachable(ctx) && ctx.allowed_tool(crate::ask::ASK_USER) {
571 #[cfg(feature = "agent86ui")]
572 let drawing = ctx.ui.is_some() && ctx.allowed_tool(crate::agent86ui::RENDER_UI);
573 #[cfg(not(feature = "agent86ui"))]
574 let drawing = false;
575 system.content = format!(
576 "{}\n\n{}",
577 system.content,
578 crate::ask::prompt_section(drawing)
579 );
580 }
581 #[cfg(feature = "agent86ui")]
584 if let Some(ui) = ctx.ui.as_deref() {
585 if ctx.allowed_tool(crate::agent86ui::RENDER_UI) {
586 system.content = format!("{}\n\n{}", system.content, ui.prompt_section());
587 }
588 }
589 if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
590 system.content = format!("{}\n\n{extra}", system.content);
591 }
592 system
593 }
594
595 pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
603 self.context_budget_with(
604 system,
605 specs,
606 self.active_context_window(),
607 self.output_cap(),
608 self.active_provider().model(),
609 )
610 }
611
612 pub(crate) fn cap_result(&self, content: String, budget: u64) -> String {
615 if !self.limits.context_sizing {
616 return content;
617 }
618 shorten_middle(
619 &content,
620 result_cap(budget, self.context.policy.max_output_chars),
621 )
622 }
623
624 pub(crate) fn request_view(
627 &self,
628 messages: &[Message],
629 budget: u64,
630 ) -> crate::memory::sizing::Aged {
631 if self.limits.context_sizing {
632 aged_view(messages, budget)
633 } else {
634 crate::memory::sizing::Aged {
635 messages: messages.to_vec(),
636 aged: 0,
637 }
638 }
639 }
640
641 pub(crate) fn context_budget_with(
647 &self,
648 system: &Message,
649 specs: &[ToolSpec],
650 window: u64,
651 output_cap: u32,
652 model: &str,
653 ) -> u64 {
654 let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
655 let (ratio, reserve) = if self.limits.context_sizing {
656 (
657 self.calibration.ratio(model),
658 sized_reserve(self.limits.context_reserve_tokens, window),
659 )
660 } else {
661 (1.0, self.limits.context_reserve_tokens)
662 };
663 calibrated_budget(
664 window,
665 overhead,
666 reserve,
667 u64::from(output_cap),
668 self.limits.max_context_tokens,
669 ratio,
670 )
671 }
672
673 fn request_tools(&self) -> Vec<ToolSpec> {
676 let mut tools = self.registry.specs();
677 tools.retain(|spec| self.context.scope_allows(&spec.name));
678 tools
679 }
680
681 pub(crate) async fn write_summary(&self, messages: &[Message]) -> WrittenSummary {
689 let (summarizer, window) = self.summary_model();
690 let model = summarizer.model().to_owned();
691 let first_cap = SUMMARY_MAX_TOKENS * 2;
692 let share = |divisor: u64| u32::try_from(window / divisor).unwrap_or(u32::MAX);
696 let retry_cap = (SUMMARY_MAX_TOKENS * 8)
697 .min(share(4))
698 .max(first_cap.min(share(2)));
699 let instructions = message(Role::System, SUMMARY_SYSTEM_PROMPT);
700 let overhead = count_tokens(std::slice::from_ref(&instructions))
701 + count_tokens(&[message(Role::User, SUMMARY_RETRY_NOTE)])
702 + SUMMARY_MARGIN_TOKENS;
703 let room = window
704 .saturating_sub(overhead + u64::from(retry_cap))
705 .max(MIN_TRANSCRIPT_TOKENS);
706 let transcript =
707 summary_request_text(messages, usize::try_from(room * 4).unwrap_or(usize::MAX));
708 let mut usage = Usage::default();
709 let mut attempt = 0;
710 loop {
711 let (text, cap) = if attempt == 0 {
712 (transcript.clone(), first_cap)
713 } else {
714 (format!("{transcript}\n\n{SUMMARY_RETRY_NOTE}"), retry_cap)
715 };
716 let request = CompletionRequest {
717 model: model.clone(),
718 messages: vec![instructions.clone(), message(Role::User, &text)],
719 tools: Vec::new(),
720 temperature: 0.0,
721 max_tokens: Some(cap),
723 stream: false,
724 };
725 let completion = tokio::select! {
726 biased;
727 () = self.cancel.cancelled() => {
729 return WrittenSummary { outcome: Err(SummaryError::Cancelled), usage, model };
730 }
731 completion = summarizer.complete(request) => completion,
732 };
733 let completion = match completion {
734 Ok(completion) => completion,
735 Err(error) => {
736 return WrittenSummary {
737 outcome: Err(SummaryError::Failed(format!("ProviderError: {error}"))),
738 usage,
739 model,
740 }
741 }
742 };
743 usage = usage + completion.usage;
744 let text = python_strip(&completion.text).to_owned();
745 if !text.is_empty() {
746 return WrittenSummary {
747 outcome: Ok(text),
748 usage,
749 model,
750 };
751 }
752 if attempt > 0 {
753 return WrittenSummary {
754 outcome: Err(SummaryError::Empty),
755 usage,
756 model,
757 };
758 }
759 attempt += 1;
760 }
761 }
762
763 async fn compact_if_needed(
778 &self,
779 state: &mut AgentState,
780 summary: &mut TurnSummary,
781 breaker: &mut CircuitBreaker,
782 window: &mut TurnWindow<'_>,
783 ) -> Option<Compaction> {
784 if self.limits.compaction != CompactionMode::Summarize {
785 return None;
786 }
787 let system = self.system_message();
788 let budget = self.context_budget(&system, &self.request_tools());
789 if fits(&self.request_view(&state.messages, budget).messages, budget) {
792 return None;
793 }
794 let tokens = count_tokens(&state.messages);
795 if window.retry_at.is_some_and(|at| tokens < at) {
796 return None;
797 }
798 let cut = compaction_plan(
802 &state.messages,
803 budget,
804 KEEP_RECENT,
805 window.goal,
806 window.continuation,
807 )?;
808 let sid = state.session_id.clone();
809 let end = cut.cut();
810 let replaced = cut.replaced();
811 let prefix = &state.messages[..end];
812 let dropped_tokens = count_tokens(prefix);
813 let written = self.write_summary(prefix).await;
814 summary.add_usage(&written.usage);
815 breaker.record_cost(written.usage.cost_usd);
816 let failed = |window: &mut TurnWindow<'_>, status: &str, error: Option<String>| {
817 window.retry_at = Some(tokens + (budget / 4).max(1));
818 let mut fields = vec![
819 ("status", json!(status)),
820 ("fallback", json!("drop")),
821 ("dropped", json!(replaced)),
822 ];
823 if let Some(error) = error {
824 fields.push(("error", json!(error)));
825 }
826 self.recorder.event(&sid, "compaction", fields);
827 Some(Compaction {
828 notice: compaction_failed_notice(replaced),
829 summary: None,
830 })
831 };
832 let text = match written.outcome {
833 Ok(text) => text,
834 Err(SummaryError::Cancelled) => return None,
835 Err(SummaryError::Failed(error)) => return failed(window, "failed", Some(error)),
836 Err(SummaryError::Empty) => return failed(window, "empty", None),
837 };
838 window.retry_at = None;
839
840 if let Some(memory) = &self.memory {
842 let _ = memory.record_compaction(&sid, &text, prefix);
843 }
844 let before = state.messages.len();
845 let kept = state.messages.split_off(end);
846 state.messages = match cut {
847 Cut::Earlier(_) => apply_summary(&text, kept),
848 Cut::WithinTurn { .. } => apply_progress(window.goal_text, &text, kept),
849 };
850 let removed = before - state.messages.len();
851 window.goal = match cut {
854 Cut::Earlier(_) => window.goal - removed,
855 Cut::WithinTurn { .. } => 0,
856 };
857 if let Some(start) = window.continuation.as_mut() {
858 *start -= removed;
859 }
860 if let Some(open) = state.open_turn.as_mut() {
862 open.goal = window.goal;
863 if matches!(cut, Cut::WithinTurn { .. }) {
864 open.goal_text = Some(window.goal_text.to_owned());
865 }
866 }
867 self.mark_open(state, breaker);
868 summary.compactions += 1;
869 let mut fields = vec![
870 ("status", json!("ok")),
871 ("dropped", json!(replaced)),
872 ("dropped_tokens", json!(dropped_tokens)),
873 (
874 "summary_tokens",
875 json!(count_tokens(&[message(Role::User, &text)])),
876 ),
877 ("kept", json!(state.messages.len())),
878 ("model", json!(written.model)),
879 ];
880 if matches!(cut, Cut::WithinTurn { .. }) {
881 fields.push(("scope", json!("turn")));
882 }
883 self.recorder.event(&sid, "compaction", fields);
884 if let Some(memory) = &self.memory {
887 let _ = memory.persist(state);
888 }
889 Some(Compaction {
890 notice: compacted_notice(replaced),
891 summary: Some(text),
892 })
893 }
894
895 pub async fn run_turn(
902 &self,
903 state: &mut AgentState,
904 goal: &str,
905 on_text: impl FnMut(&str),
906 ) -> Result<String, HarnessError> {
907 self.run_turn_as(state, goal, goal, on_text).await
908 }
909
910 pub async fn run_turn_as(
914 &self,
915 state: &mut AgentState,
916 user_text: &str,
917 display_text: &str,
918 mut on_text: impl FnMut(&str),
919 ) -> Result<String, HarnessError> {
920 self.run_turn_events(state, user_text, display_text, |event| {
921 on_text(event.text())
922 })
923 .await
924 }
925
926 pub async fn run_turn_events(
930 &self,
931 state: &mut AgentState,
932 user_text: &str,
933 display_text: &str,
934 on_event: impl FnMut(TurnEvent<'_>),
935 ) -> Result<String, HarnessError> {
936 self.run_turn_with(state, Start::New(user_text), display_text, None, on_event)
937 .await
938 }
939
940 pub async fn run_skill_turn(
947 &self,
948 state: &mut AgentState,
949 skill: &Arc<crate::skills::Skill>,
950 task: &str,
951 display_text: &str,
952 on_event: impl FnMut(TurnEvent<'_>),
953 ) -> Result<String, HarnessError> {
954 let user_text = crate::skills::skill_request(skill, task);
955 self.run_turn_with(
956 state,
957 Start::New(&user_text),
958 display_text,
959 Some(skill),
960 on_event,
961 )
962 .await
963 }
964
965 pub fn continuable(&self, state: &AgentState) -> Result<Continuation, NotContinuable> {
971 let refuse = |why: &str| Err(NotContinuable(why.to_owned()));
972 let Some(open) = state
973 .open_turn
974 .clone()
975 .filter(|_| state.phase != AgentPhase::Done)
976 else {
977 return refuse(
978 "there is no unfinished turn to continue: the session's last turn finished",
979 );
980 };
981 let goal = state
982 .messages
983 .get(open.goal)
984 .filter(|goal| goal.role == Role::User);
985 let Some(goal) = goal.filter(|_| open.messages == state.messages.len()) else {
986 return refuse(
987 "the session's history has changed since its last turn stopped, so that turn \
988 can't be continued",
989 );
990 };
991 let goal_text = open
992 .goal_text
993 .clone()
994 .unwrap_or_else(|| goal.content.clone());
995 let skill = match &open.skill {
996 None => None,
997 Some(name) => match self.context.skills.get(name) {
998 Some(skill) => Some(Arc::clone(skill)),
999 None => {
1000 return Err(NotContinuable(format!(
1001 "the turn was running the skill '{name}', which is no longer available"
1002 )))
1003 }
1004 },
1005 };
1006 let running = self.subagents.main_name();
1007 if running != open.agent {
1008 return Err(NotContinuable(match &open.agent {
1009 Some(name) => format!(
1010 "the turn ran as the specialist sub-agent '{name}'; continue it as that \
1011 specialist (run --agent {name})"
1012 ),
1013 None => "the turn did not run as a specialist sub-agent; continue it without one"
1014 .to_owned(),
1015 }));
1016 }
1017 Ok(Continuation {
1018 open,
1019 goal_text,
1020 skill,
1021 })
1022 }
1023
1024 pub async fn continue_turn(
1030 &self,
1031 state: &mut AgentState,
1032 continuation: &Continuation,
1033 on_event: impl FnMut(TurnEvent<'_>),
1034 ) -> Result<String, HarnessError> {
1035 let goal = without_turn_note(&continuation.goal_text).to_owned();
1036 self.run_turn_with(
1037 state,
1038 Start::Continue(continuation),
1039 &goal,
1040 continuation.skill.as_ref(),
1041 on_event,
1042 )
1043 .await
1044 }
1045
1046 fn mark_open(&self, state: &mut AgentState, breaker: &CircuitBreaker) {
1049 let messages = state.messages.len();
1050 if let Some(open) = state.open_turn.as_mut() {
1051 open.messages = messages;
1052 open.steps = breaker.steps;
1053 open.cost_usd = breaker.cost_usd;
1054 open.consecutive_errors = breaker.consecutive_errors;
1055 open.skill = self.context.active_skill().map(|skill| skill.name.clone());
1056 }
1057 }
1058
1059 async fn run_turn_with(
1060 &self,
1061 state: &mut AgentState,
1062 start: Start<'_>,
1063 display_text: &str,
1064 skill: Option<&Arc<crate::skills::Skill>>,
1065 on_event: impl FnMut(TurnEvent<'_>),
1066 ) -> Result<String, HarnessError> {
1067 self.cancel.clear();
1069 self.context.clear_skill();
1074 if let Some(skill) = skill {
1075 self.context.activate_skill(skill);
1076 }
1077 let started = Instant::now();
1078 let mut span = self.tracer.start(
1080 "turn",
1081 vec![
1082 ("session.id", json!(state.session_id)),
1083 (
1084 "gen_ai.request.model",
1085 json!(self.active_provider().model()),
1086 ),
1087 ],
1088 );
1089 let mut summary = TurnSummary::default();
1090 let secrets = &self.context.secrets;
1093 let display_text = secrets.redact(display_text);
1094 let mut limits = self.limits.clone();
1095 limits.max_steps = self.max_steps();
1096 let mut breaker = CircuitBreaker::new(&limits);
1097 let result = match start {
1098 Start::New(user_text) => {
1099 state.open_turn = None;
1101 let user_text = secrets.redact(user_text);
1102 self.turn(
1103 state,
1104 Start::New(&user_text),
1105 &display_text,
1106 &mut summary,
1107 &mut breaker,
1108 on_event,
1109 )
1110 .await
1111 }
1112 Start::Continue(continuation) => {
1113 breaker.carry_over(&continuation.open);
1114 state.open_turn = Some(continuation.open.clone());
1115 self.turn(
1116 state,
1117 start,
1118 &display_text,
1119 &mut summary,
1120 &mut breaker,
1121 on_event,
1122 )
1123 .await
1124 }
1125 };
1126 if state.phase == AgentPhase::Done {
1129 state.open_turn = None;
1130 } else {
1131 self.mark_open(state, &breaker);
1132 }
1133 self.context.clear_skill();
1134 summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
1135 state.last_turn = Some(summary);
1136 if let Err(error) = &result {
1137 state.phase = AgentPhase::Error;
1138 let reason = match error {
1139 HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
1140 HarnessError::Provider(detail) => {
1141 format!("provider stream failed: ProviderError: {detail}")
1142 }
1143 HarnessError::NoFinalCompletion { .. } => {
1144 "provider stream ended without a final completion".to_owned()
1145 }
1146 };
1147 self.recorder.event(
1148 &state.session_id,
1149 "turn_end",
1150 vec![("status", json!("error")), ("reason", json!(reason))],
1151 );
1152 }
1153 span.set(turn_attributes(state, self.active_provider().model()));
1156 if let Err(error) = &result {
1157 span.fail(error.python_type(), &error.to_string());
1158 }
1159 self.tracer.end(span);
1160 result
1161 }
1162
1163 async fn turn(
1164 &self,
1165 state: &mut AgentState,
1166 start: Start<'_>,
1167 display_text: &str,
1168 summary: &mut TurnSummary,
1169 breaker: &mut CircuitBreaker,
1170 mut on_event: impl FnMut(TurnEvent<'_>),
1171 ) -> Result<String, HarnessError> {
1172 let (goal, continuing) = match start {
1173 Start::New(goal) => (goal, None),
1174 Start::Continue(continuation) => (
1177 without_turn_note(&continuation.goal_text),
1178 Some(continuation),
1179 ),
1180 };
1181 let mut output = String::new();
1182 let mut emit = |event: TurnEvent<'_>| {
1183 output.push_str(event.text());
1184 on_event(event);
1185 };
1186
1187 let sid = state.session_id.clone();
1188 let mut fields = vec![("task", json!(display_text))];
1189 if let Some(continuation) = continuing {
1190 fields.push(("continued", json!(true)));
1192 fields.push(("from_step", json!(continuation.open.steps)));
1193 }
1194 self.recorder.event(&sid, "turn_start", fields);
1195 self.verify.set_last(None);
1196 if let Some(continuation) = continuing {
1197 emit(TurnEvent::Notice(&continued_notice(
1198 continuation.open.steps,
1199 )));
1200 }
1201
1202 let report = match continuing {
1204 None => self.guardrails.inspect_ingress(goal),
1205 Some(_) => Default::default(),
1206 };
1207 if report.flagged() {
1208 self.recorder.event(
1209 &sid,
1210 "guardrail",
1211 vec![
1212 ("stage", json!("ingress_input")),
1213 ("findings", json!(report.summary())),
1214 ],
1215 );
1216 if self.guardrails.should_block(&report) {
1217 let refusal = format!(
1218 "Refused: input tripped the ingress guardrail ({}).",
1219 report.summary()
1220 );
1221 state.messages.push(message(Role::User, goal));
1222 state.messages.push(message(Role::Assistant, &refusal));
1223 state.phase = AgentPhase::Error;
1224 self.recorder
1225 .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
1226 emit(TurnEvent::Text(&refusal));
1227 return Ok(output);
1228 }
1229 emit(TurnEvent::Notice(&format!(
1230 "[guardrail] input flagged: {}\n",
1231 report.summary()
1232 )));
1233 }
1234
1235 let buffering = self.guardrails.egress == EgressMode::Redact;
1238
1239 self.route(goal, &sid)?;
1241 let provider = self.active_provider();
1242
1243 let recall_note = self
1245 .memory
1246 .as_ref()
1247 .and_then(|memory| memory.recall_note(goal));
1248 let time = time_note(&jiff::ZonedDateTime::now());
1252 let note = match recall_note {
1253 Some(recalled) => format!("{time}\n\n{recalled}"),
1254 None => time,
1255 };
1256 let (noted, continued_note) = match continuing {
1261 None => (with_turn_note(goal, ¬e), None),
1262 Some(continuation) => (
1263 continuation.goal_text.clone(),
1264 Some(format!("{note}\n\n{CONTINUED_NOTE}")),
1265 ),
1266 };
1267 let mut window = TurnWindow {
1271 goal_text: ¬ed,
1272 goal: continuing.map_or(state.messages.len(), |continuation| continuation.open.goal),
1273 continuation: None,
1274 retry_at: None,
1275 trim_announced: false,
1276 trimmed: 0,
1277 aged: 0,
1278 };
1279 let base_steps = breaker.steps();
1282 if continuing.is_none() {
1283 state.messages.push(message(Role::User, ¬ed));
1284 state.open_turn = Some(OpenTurn {
1285 goal: window.goal,
1286 messages: state.messages.len(),
1287 skill: self.context.active_skill().map(|skill| skill.name.clone()),
1288 agent: self.subagents.main_name(),
1289 ..OpenTurn::default()
1290 });
1291 } else {
1292 let answered = answer_unrecorded(&mut state.messages, window.goal);
1293 if answered > 0 {
1294 self.mark_open(state, breaker);
1295 }
1296 }
1297 let mut broken_streak = BrokenStreak::default();
1298 let mut continuation_start: Option<usize> = None;
1300 let mut continuation_parts: Vec<String> = Vec::new();
1301 let mut nudged = false;
1305 let mut ask_again = false;
1306 let mut unanswered_thinking = String::new();
1307 let mut reasoning_loops = 0u32;
1310 let mut verify_run = crate::verify::VerifyRun::default();
1312 if let Some(continuation) = continuing {
1314 let taken = continuation.open.steps as usize;
1315 for step in state.steps.iter().rev().take(taken) {
1316 for result in &step.results {
1317 verify_run.saw(&result.name, result.ok);
1318 }
1319 }
1320 }
1321 let mut stall = crate::stall::StallWatch::new(self.limits.stall_nudge);
1323
1324 loop {
1325 if self.cancel.is_cancelled() {
1328 self.cancelled(state, breaker.steps(), &mut emit);
1329 return Ok(output);
1330 }
1331 if breaker.out_of_steps() {
1333 match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
1334 Some(raised) => breaker.set_max_steps(raised),
1335 None if self.cancel.is_cancelled() => {
1337 self.cancelled(state, breaker.steps(), &mut emit);
1338 return Ok(output);
1339 }
1340 None => {}
1341 }
1342 }
1343 breaker.before_step()?;
1344
1345 window.continuation = continuation_start;
1348 if let Some(compaction) = self
1349 .compact_if_needed(state, summary, breaker, &mut window)
1350 .await
1351 {
1352 continuation_start = window.continuation;
1353 window.trim_announced = compaction.summary.is_none();
1356 emit(TurnEvent::Compacted {
1359 notice: &compaction.notice,
1360 summary: compaction.summary.as_deref(),
1361 });
1362 }
1363
1364 let estimated;
1367 let step_budget;
1368 let mut completion = {
1369 let system = self.system_message();
1370 let tools = self.request_tools();
1372 let budget = self.context_budget(&system, &tools);
1373 step_budget = budget;
1374 let sent = request_goal(&state.messages, window.goal, continued_note.as_deref());
1376 let aged = self.request_view(&sent, budget);
1377 self.announce_age(&sid, aged.aged, budget, &mut window);
1378 let fitted = fit_pinned(&aged.messages, budget, Some(window.goal));
1379 self.announce_trim(&sid, &fitted, budget, &mut window, &mut emit);
1380 let mut request_messages = Vec::with_capacity(fitted.messages.len() + 1);
1381 request_messages.push(system);
1382 request_messages.extend(fitted.messages);
1383 if std::mem::take(&mut ask_again) {
1384 request_messages.push(message(Role::User, ANSWER_PROMPT));
1385 }
1386 estimated = count_tokens(&request_messages) + count_spec_tokens(&tools);
1387 let request = CompletionRequest {
1388 model: provider.model().to_owned(),
1389 messages: request_messages,
1390 tools,
1391 temperature: request_temperature(
1393 provider.as_ref(),
1394 self.subagents.main().and_then(|main| main.2),
1395 ),
1396 max_tokens: Some(self.output_cap()),
1397 stream: true,
1398 };
1399 let mut span = self.tracer.start(
1401 "model_call",
1402 vec![
1403 ("gen_ai.system", json!(provider.name())),
1404 ("gen_ai.request.model", json!(provider.model())),
1405 ("agent86.step", json!(breaker.steps() + 1)),
1406 ],
1407 );
1408 let mut stream = provider.stream(request);
1409 let mut completion = None;
1410 let mut buffered = String::new();
1411 let mut redactor = StreamRedactor::default();
1414 let mut thinking_redactor = StreamRedactor::default();
1415 loop {
1416 let next = tokio::select! {
1419 biased;
1420 () = self.cancel.cancelled() => None,
1421 delta = stream.next() => Some(delta),
1422 };
1423 let Some(Some(delta)) = next else { break };
1424 let delta = match delta {
1425 Ok(delta) => delta,
1426 Err(error) => {
1427 span.set(model_call_attributes(None));
1428 span.fail("ProviderError", &error.to_string());
1429 self.tracer.end(span);
1430 return Err(error.into());
1431 }
1432 };
1433 if !delta.thinking.is_empty() && !buffering {
1436 let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
1437 if !shown.is_empty() {
1438 emit(TurnEvent::Thinking(&shown));
1439 }
1440 }
1441 if !delta.text.is_empty() {
1442 if buffering {
1443 buffered.push_str(&delta.text);
1444 } else {
1445 let shown = redactor.push(&self.context.secrets, &delta.text);
1446 if !shown.is_empty() {
1447 emit(TurnEvent::Text(&shown));
1448 }
1449 }
1450 }
1451 if delta.done && delta.completion.is_some() {
1452 completion = delta.completion;
1453 }
1454 }
1455 drop(stream);
1456 let held = thinking_redactor.finish(&self.context.secrets);
1457 if !held.is_empty() {
1458 emit(TurnEvent::Thinking(&held));
1459 }
1460 let held = redactor.finish(&self.context.secrets);
1461 if !held.is_empty() {
1462 emit(TurnEvent::Text(&held));
1463 }
1464 span.set(model_call_attributes(completion.as_ref()));
1465 self.tracer.end(span);
1466 if self.cancel.is_cancelled() {
1467 let partial = self
1469 .guardrails
1470 .inspect_egress(&self.context.secrets.redact(&buffered))
1471 .1;
1472 if !partial.is_empty() {
1473 emit(TurnEvent::Text(&partial));
1474 }
1475 self.cancelled(state, breaker.steps(), &mut emit);
1476 return Ok(output);
1477 }
1478 completion.ok_or_else(|| HarnessError::NoFinalCompletion {
1479 provider: provider.name().to_owned(),
1480 model: provider.model().to_owned(),
1481 })?
1482 };
1483
1484 breaker.record_step(&completion.usage);
1485 if self.limits.context_sizing {
1486 self.calibration.observe(
1487 provider.model(),
1488 estimated,
1489 completion.usage.input_tokens,
1490 );
1491 }
1492 summary.steps = u64::from(breaker.steps() - base_steps);
1493 summary.add_usage(&completion.usage);
1494 emit(TurnEvent::Usage {
1497 step: &completion.usage,
1498 session: &(state.usage + completion.usage),
1499 });
1500 let names: Vec<&str> = completion
1501 .tool_calls
1502 .iter()
1503 .map(|call| call.name.as_str())
1504 .collect();
1505 self.recorder.event(
1506 &sid,
1507 "model_call",
1508 vec![
1509 ("step", json!(breaker.steps())),
1510 ("model", json!(provider.model())),
1511 ("input_tokens", json!(completion.usage.input_tokens)),
1512 ("output_tokens", json!(completion.usage.output_tokens)),
1513 ("cost_usd", json!(completion.usage.cost_usd)),
1514 ("stop_reason", json!(completion.stop_reason)),
1515 ("tool_calls", json!(names)),
1516 ],
1517 );
1518
1519 if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
1520 emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
1521 reasoning_loops += 1;
1522 if reasoning_loops == 2 && provider.name() == "ollama" {
1523 emit(TurnEvent::Notice(&ollama_loop_hint(provider.model())));
1524 }
1525 }
1526 let stopped = completion
1530 .stop_reason
1531 .as_deref()
1532 .and_then(|reason| reason.strip_prefix(crate::provider::STOPPED_PREFIX))
1533 .map(str::to_owned);
1534 if let Some(reason) = &stopped {
1535 emit(TurnEvent::Notice(&format!(
1536 "\n[{} stopped the reply: {reason}]\n",
1537 provider.name()
1538 )));
1539 }
1540
1541 let mut from_thinking = false;
1547 if completion.tool_calls.is_empty()
1548 && completion.stop_reason.as_deref() != Some("max_tokens")
1549 && stopped.is_none()
1550 && completion.text.trim().is_empty()
1551 && continuation_start.is_none()
1552 {
1553 if !completion.thinking.trim().is_empty() {
1554 unanswered_thinking = std::mem::take(&mut completion.thinking);
1555 }
1556 if !nudged && !breaker.out_of_steps() {
1557 nudged = true;
1558 ask_again = true;
1559 self.recorder.event(
1560 &sid,
1561 "empty_answer",
1562 vec![
1563 ("step", json!(breaker.steps())),
1564 ("model", json!(provider.model())),
1565 ("thinking_chars", json!(unanswered_thinking.chars().count())),
1566 ],
1567 );
1568 record_step(
1569 state,
1570 Step {
1571 index: state.steps.len() as u64 + 1,
1572 phase: AgentPhase::Execute,
1573 thought: String::new(),
1574 tool_calls: Vec::new(),
1575 results: Vec::new(),
1576 usage: completion.usage,
1577 },
1578 );
1579 self.checkpoint(state, breaker);
1580 emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1581 continue;
1582 }
1583 if unanswered_thinking.trim().is_empty() {
1584 emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1585 if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1588 emit(TurnEvent::Notice(&format!(
1589 "{}\n",
1590 crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1591 )));
1592 }
1593 } else {
1594 completion.text = std::mem::take(&mut unanswered_thinking);
1595 from_thinking = true;
1596 emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1597 }
1598 }
1599
1600 let answer = self.context.secrets.redact(&completion.text);
1603 let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1604 let text = if buffering {
1605 if !redacted.is_empty() {
1606 emit(TurnEvent::Text(&redacted));
1607 }
1608 redacted
1609 } else {
1610 if from_thinking {
1612 emit(TurnEvent::Text(&answer));
1613 }
1614 answer
1615 };
1616 if egress.flagged() {
1617 self.recorder.event(
1618 &sid,
1619 "guardrail",
1620 vec![
1621 ("stage", json!("egress")),
1622 ("findings", json!(egress.summary())),
1623 ],
1624 );
1625 emit(TurnEvent::Notice(&format!(
1626 "\n[guardrail] output flagged: {}\n",
1627 egress.summary()
1628 )));
1629 }
1630 let mut tool_calls = completion.tool_calls;
1631 let repairs = self.repair_broken_calls(&mut tool_calls, &sid);
1633 self.scan_tool_arguments(&tool_calls, &sid);
1634 let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1635 if cut_off
1640 && tool_calls.is_empty()
1641 && text.trim().is_empty()
1642 && continuation_start.is_none()
1643 {
1644 let cap = self.output_cap();
1645 if self
1646 .raise_limit(LimitKind::Output, None, &sid, cap, false)
1647 .is_some()
1648 {
1649 record_step(
1650 state,
1651 Step {
1652 index: state.steps.len() as u64 + 1,
1653 phase: AgentPhase::Execute,
1654 thought: String::new(),
1655 tool_calls: Vec::new(),
1656 results: Vec::new(),
1657 usage: completion.usage,
1658 },
1659 );
1660 self.checkpoint(state, breaker);
1661 continue;
1662 }
1663 }
1664 let mut step = Step {
1665 index: state.steps.len() as u64 + 1,
1666 phase: AgentPhase::Execute,
1667 thought: text.clone(),
1668 tool_calls: tool_calls.clone(),
1669 results: Vec::new(),
1670 usage: completion.usage,
1671 };
1672 state.messages.push(Message {
1673 tool_calls: tool_calls.clone(),
1674 ..message(Role::Assistant, &text)
1675 });
1676
1677 if tool_calls.is_empty() {
1678 if cut_off && summary.continuations < MAX_CONTINUATIONS {
1679 summary.continuations += 1;
1680 continuation_start.get_or_insert(state.messages.len() - 1);
1681 continuation_parts.push(text);
1682 state.messages.push(message(Role::User, CONTINUE_PROMPT));
1683 record_step(state, step);
1684 self.checkpoint(state, breaker);
1685 self.recorder.event(
1686 &sid,
1687 "continuation",
1688 vec![
1689 ("index", json!(summary.continuations)),
1690 ("step", json!(breaker.steps())),
1691 ("model", json!(provider.model())),
1692 (
1693 "chars",
1694 json!(continuation_parts
1695 .last()
1696 .map_or(0, |part| part.chars().count())),
1697 ),
1698 ],
1699 );
1700 emit(TurnEvent::Notice(&continuation_notice(
1701 summary.continuations,
1702 )));
1703 continue;
1704 }
1705 if let Some(start) = continuation_start.take() {
1706 continuation_parts.push(text);
1708 let joined = std::mem::take(&mut continuation_parts).concat();
1709 state.messages.truncate(start);
1710 state.messages.push(message(Role::Assistant, &joined));
1711 step.thought = joined;
1712 }
1713 let steps_left = !breaker.out_of_steps();
1716 if let crate::verify::Gate::SendBack(feedback) =
1717 self.verify_answer(&mut verify_run, steps_left, &sid, &mut emit)
1718 {
1719 record_step(state, step);
1720 state.messages.push(message(Role::User, &feedback));
1721 self.checkpoint(state, breaker);
1722 continue;
1723 }
1724 let outcome = step.thought.clone();
1725 record_step(state, step);
1726 state.phase = AgentPhase::Done;
1727 self.recorder.event(
1728 &sid,
1729 "turn_end",
1730 vec![
1731 ("status", json!("done")),
1732 ("steps", json!(breaker.steps())),
1733 ("continuations", json!(summary.continuations)),
1734 ],
1735 );
1736 if let Some(memory) = &self.memory {
1737 let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1739 }
1740 return Ok(output);
1741 }
1742
1743 continuation_start = None;
1745 continuation_parts.clear();
1746
1747 if self.cancel.is_cancelled() {
1751 for call in &tool_calls {
1752 let result = not_executed(call, "cancelled");
1753 state.messages.push(Message {
1754 tool_call_id: Some(call.id.clone()),
1755 name: Some(call.name.clone()),
1756 ..message(Role::Tool, &observation(&result))
1757 });
1758 step.results.push(result);
1759 }
1760 record_step(state, step);
1761 self.cancelled(state, breaker.steps(), &mut emit);
1762 return Ok(output);
1763 }
1764
1765 for call in &tool_calls {
1767 let text = format!(
1768 "\n[tool] {}({})\n",
1769 call.name,
1770 preview_arguments(&call.arguments)
1771 );
1772 emit(TurnEvent::ToolCall { call, text: &text });
1773 }
1774 let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1775 for notice in self.take_notices() {
1779 emit(TurnEvent::Notice(&format!("{notice}\n")));
1780 }
1781 let mut asked_in_text: Option<String> = None;
1783 let mut tripped: Option<HarnessError> = None;
1786 for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1787 summary.tool_calls += 1;
1788 if tripped.is_some() {
1789 let content = self.observe(call, &result, step_budget, &sid);
1792 emit(TurnEvent::ToolResult {
1793 call,
1794 result: &result,
1795 observation: &content,
1796 text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1797 });
1798 state.messages.push(Message {
1799 tool_call_id: Some(call.id.clone()),
1800 name: Some(call.name.clone()),
1801 ..message(Role::Tool, &content)
1802 });
1803 step.results.push(result);
1804 summary.add_usage(&delegated);
1805 step.usage = step.usage + delegated;
1806 breaker.record_cost(delegated.cost_usd);
1807 continue;
1808 }
1809 #[cfg(feature = "agent86ui")]
1812 let result = {
1813 let mut result = result;
1814 let (drawn, trace) = crate::agent86ui::take_drawn(&mut result.metadata);
1815 for message in &drawn {
1816 emit(TurnEvent::Ui(message));
1817 }
1818 if let Some(Value::Object(fields)) = trace {
1819 let fields: Vec<(&str, Value)> = fields
1822 .iter()
1823 .map(|(key, value)| (key.as_str(), value.clone()))
1824 .collect();
1825 self.recorder.event(&sid, "ui_render", fields);
1826 }
1827 match crate::agent86ui::take_wait(&mut result.metadata) {
1830 Some(surfaces) => self.ui_wait(call, result, surfaces, &sid),
1831 None => result,
1832 }
1833 };
1834 let mut result = self.ask_questions(call, result, &sid, &mut emit);
1837 if let Some(Value::String(text)) = result.metadata.remove(crate::ask::ASK_TEXT_KEY)
1838 {
1839 asked_in_text = Some(match asked_in_text.take() {
1840 Some(earlier) => format!("{earlier}\n\n{text}"),
1841 None => text,
1842 });
1843 }
1844 let result = self.annotate_broken_json(call, result, &repairs, &mut broken_streak);
1845 summary.add_usage(&delegated);
1848 step.usage = step.usage + delegated;
1849 breaker.record_cost(delegated.cost_usd);
1850 let content = self.observe(call, &result, step_budget, &sid);
1851 emit(TurnEvent::ToolResult {
1852 call,
1853 result: &result,
1854 observation: &content,
1855 text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1856 });
1857 state.messages.push(Message {
1858 tool_call_id: Some(call.id.clone()),
1859 name: Some(call.name.clone()),
1860 ..message(Role::Tool, &content)
1861 });
1862 let ok = result.ok;
1863 verify_run.saw(&call.name, ok);
1864 stall.saw(call, &result, &content);
1865 step.results.push(result);
1866 if let Err(error) = breaker.record_tool_result(ok) {
1867 tripped = Some(error);
1868 }
1869 }
1870 if let Some(error) = tripped {
1871 record_step(state, step);
1872 return Err(error);
1873 }
1874 if let Some(questions) = asked_in_text {
1880 emit(TurnEvent::Text(&questions));
1881 state.messages.push(message(Role::Assistant, &questions));
1882 record_step(state, step);
1883 state.phase = AgentPhase::Done;
1884 self.recorder.event(
1885 &sid,
1886 "turn_end",
1887 vec![
1888 ("status", json!("done")),
1889 ("steps", json!(breaker.steps())),
1890 ("continuations", json!(summary.continuations)),
1891 ],
1892 );
1893 if let Some(memory) = &self.memory {
1894 let _ = memory.add_episode(&sid, goal, &questions, &Default::default());
1895 }
1896 return Ok(output);
1897 }
1898 if let Some(found) = stall.take() {
1901 self.remind_of_stall(&found, &sid, &mut emit);
1902 state.messages.push(message(Role::User, &found.note()));
1903 }
1904 record_step(state, step);
1905 self.checkpoint(state, breaker);
1906 if self.cancel.is_cancelled() {
1907 self.cancelled(state, breaker.steps(), &mut emit);
1908 return Ok(output);
1909 }
1910 }
1911 }
1912
1913 fn checkpoint(&self, state: &mut AgentState, breaker: &CircuitBreaker) {
1920 state.phase = AgentPhase::Execute;
1921 self.mark_open(state, breaker);
1922 if let Some(memory) = &self.memory {
1923 let _ = memory.persist(state);
1924 }
1925 }
1926
1927 fn announce_trim(
1934 &self,
1935 sid: &str,
1936 fitted: &Fitted,
1937 budget: u64,
1938 window: &mut TurnWindow<'_>,
1939 emit: &mut impl FnMut(TurnEvent<'_>),
1940 ) {
1941 if fitted.dropped == window.trimmed {
1942 return;
1943 }
1944 window.trimmed = fitted.dropped;
1945 if fitted.dropped == 0 {
1946 return;
1947 }
1948 self.recorder.event(
1949 sid,
1950 "context_trim",
1951 vec![
1952 ("dropped", json!(fitted.dropped)),
1953 ("kept", json!(fitted.messages.len())),
1954 ("budget", json!(budget)),
1955 ("goal_pinned", json!(fitted.pinned)),
1956 ],
1957 );
1958 if !window.trim_announced {
1959 window.trim_announced = true;
1960 emit(TurnEvent::Notice(&trimmed_notice(fitted.dropped)));
1961 }
1962 }
1963
1964 fn remind_of_stall(
1968 &self,
1969 found: &crate::stall::Stall,
1970 sid: &str,
1971 emit: &mut impl FnMut(TurnEvent<'_>),
1972 ) {
1973 emit(TurnEvent::Notice(&found.notice()));
1974 let mut fields = vec![
1975 ("shape", json!(found.kind.as_str())),
1976 ("count", json!(found.count)),
1977 ];
1978 if let Some(tool) = &found.tool {
1979 fields.push(("tool", json!(tool)));
1980 }
1981 self.recorder.event(sid, "stall", fields);
1982 }
1983
1984 fn announce_age(&self, sid: &str, aged: usize, budget: u64, window: &mut TurnWindow<'_>) {
1988 if aged == window.aged {
1989 return;
1990 }
1991 window.aged = aged;
1992 self.recorder.event(
1993 sid,
1994 "context_age",
1995 vec![("aged", json!(aged)), ("budget", json!(budget))],
1996 );
1997 }
1998
1999 fn observe(&self, call: &ToolCall, result: &ToolResult, budget: u64, sid: &str) -> String {
2002 let (content, findings) = self.guardrails.observe(observation(result));
2003 let content = self.cap_result(content, budget);
2004 if let Some(findings) = findings {
2005 self.recorder.event(
2006 sid,
2007 "guardrail",
2008 vec![
2009 ("stage", json!("observation")),
2010 ("tool", json!(call.name)),
2011 ("findings", json!(findings)),
2012 ],
2013 );
2014 }
2015 content
2016 }
2017
2018 fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
2019 state.phase = AgentPhase::Error;
2020 self.recorder.event(
2021 &state.session_id,
2022 "turn_end",
2023 vec![
2024 ("status", json!("cancelled")),
2025 ("reason", json!("cancelled")),
2026 ("steps", json!(steps)),
2027 ],
2028 );
2029 emit(TurnEvent::Notice(CANCELLED_NOTICE));
2030 }
2031
2032 async fn execute_batch(
2046 &self,
2047 calls: &[ToolCall],
2048 sid: &str,
2049 spent: f64,
2050 ) -> Vec<(ToolResult, Usage)> {
2051 let eligible = calls
2052 .iter()
2053 .filter(|call| self.parallel_eligible(call))
2054 .count();
2055 let specialty: Vec<bool> = calls
2056 .iter()
2057 .map(|call| self.is_specialty_delegation(call))
2058 .collect();
2059 let any_specialty = specialty.contains(&true);
2060 if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
2061 let mut results = Vec::with_capacity(calls.len());
2063 for call in calls {
2064 results.push(if self.cancel.is_cancelled() {
2065 (not_executed(call, "cancelled"), Usage::default())
2066 } else {
2067 self.execute_tool(call, sid).await
2068 });
2069 }
2070 return results;
2071 }
2072
2073 let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
2074 let mut may_parallel = Vec::with_capacity(calls.len());
2075 for call in calls {
2076 let (result, parallel) = self.resolve_call(call, sid);
2077 settled.push(result.map(|result| (result, Usage::default())));
2078 may_parallel.push(parallel);
2079 }
2080 let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
2081 let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
2082 let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
2083
2084 if reads.len() > 1 {
2085 let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
2086 let handles: Vec<_> = reads
2087 .iter()
2088 .map(|&index| {
2089 (
2090 index,
2091 scope.spawn(move || self.dispatch(&calls[index], sid)),
2092 )
2093 })
2094 .collect();
2095 handles
2096 .into_iter()
2097 .map(|(index, handle)| {
2098 let result = handle
2099 .join()
2100 .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
2101 (index, result)
2102 })
2103 .collect()
2104 });
2105 for (index, result) in collected {
2106 settled[index] = Some((result, Usage::default()));
2107 }
2108 } else {
2109 for &index in &reads {
2110 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
2111 }
2112 }
2113 let mut next = 0;
2117 while next < writes.len() {
2118 let index = writes[next];
2119 let run_end = writes[next..]
2120 .iter()
2121 .position(|&index| !specialty[index])
2122 .map_or(writes.len(), |offset| next + offset);
2123 if specialty[index] && run_end - next > 1 {
2124 let group: Vec<usize> = writes[next..run_end].to_vec();
2125 let results = if self.cancel.is_cancelled() {
2126 group
2127 .iter()
2128 .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
2129 .collect()
2130 } else {
2131 let members: Vec<&ToolCall> =
2132 group.iter().map(|&index| &calls[index]).collect();
2133 self.fan_out(&members, sid, spent)
2134 };
2135 for (index, result) in group.into_iter().zip(results) {
2136 settled[index] = Some(result);
2137 }
2138 next = run_end;
2139 } else {
2140 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
2141 next += 1;
2142 }
2143 }
2144
2145 settled
2146 .into_iter()
2147 .zip(calls)
2148 .map(|(result, call)| {
2149 result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
2150 })
2151 .collect()
2152 }
2153
2154 fn parallel_eligible(&self, call: &ToolCall) -> bool {
2157 call.invalid_arguments().is_none()
2158 && self
2159 .registry
2160 .get(&call.name)
2161 .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
2162 }
2163
2164 pub(crate) fn resolve_call(&self, call: &ToolCall, sid: &str) -> (Option<ToolResult>, bool) {
2173 let settled = |result: ToolResult| {
2174 self.record_tool_call(call, &result, sid);
2175 (Some(result), false)
2176 };
2177 if let Some(raw) = call.invalid_arguments() {
2178 return settled(invalid_arguments_result(call, raw));
2179 }
2180 let Some(tool) = self.registry.get(&call.name) else {
2181 return settled(self.registry.dispatch(call, &self.context));
2183 };
2184 if !self.context.scope_allows(&call.name) {
2187 return settled(self.registry.dispatch(call, &self.context));
2188 }
2189 let decision = self.gate.decide(tool.as_ref(), call, &self.context);
2190 if !decision.approved {
2191 return settled(not_executed(call, decision.reason));
2192 }
2193 (None, !tool.side_effecting() && tool.parallel_safe())
2194 }
2195
2196 async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
2197 if self.cancel.is_cancelled() {
2198 (not_executed(call, "cancelled"), Usage::default())
2199 } else {
2200 self.dispatch_call(call, sid).await
2201 }
2202 }
2203
2204 async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
2207 let request = match self.delegation(call, &self.context) {
2208 Some(request) => request,
2209 None => return (self.dispatch(call, sid), Usage::default()),
2210 };
2211 let mut span = self.tool_span(call);
2212 let (result, usage) = match request {
2213 Ok(request) => self.delegate(call, request, 1, &self.context).await,
2214 Err(invalid) => (invalid, Usage::default()),
2215 };
2216 span.set(vec![("tool.ok", json!(result.ok))]);
2217 self.tracer.end(span);
2218 self.record_tool_call(call, &result, sid);
2219 (result, usage)
2220 }
2221
2222 pub(crate) fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
2224 let mut span = self.tool_span(call);
2225 let result = self.registry.dispatch(call, &self.context);
2226 span.set(vec![("tool.ok", json!(result.ok))]);
2227 self.tracer.end(span);
2228 self.record_tool_call(call, &result, sid);
2229 result
2230 }
2231
2232 pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
2234 self.tracer.start(
2235 "tool_call",
2236 vec![
2237 ("tool.name", json!(call.name)),
2238 ("gen_ai.tool.name", json!(call.name)),
2239 ],
2240 )
2241 }
2242
2243 pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
2244 self.recorder.event(
2245 sid,
2246 "tool_call",
2247 vec![
2248 ("tool", json!(call.name)),
2249 ("ok", json!(result.ok)),
2250 ("arguments", Value::Object(call.arguments.clone())),
2251 ("error", json!(result.error)),
2252 ],
2253 );
2254 self.record_repair(call, result, sid);
2255 }
2256
2257 pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
2260 if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
2261 self.recorder.event(
2262 sid,
2263 "tool_args_repaired",
2264 vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
2265 );
2266 }
2267 }
2268
2269 pub(crate) fn repair_broken_calls(
2277 &self,
2278 calls: &mut [ToolCall],
2279 sid: &str,
2280 ) -> HashMap<String, String> {
2281 let mut notes = HashMap::new();
2282 for call in calls.iter_mut() {
2283 let Some(raw) = call.invalid_arguments() else {
2284 continue;
2285 };
2286 let Some((arguments, dropped)) = crate::broken_json::drop_unmatched_closers(raw) else {
2287 continue;
2288 };
2289 self.recorder.event(
2290 sid,
2291 "tool_args_repaired",
2292 vec![
2293 ("tool", json!(call.name)),
2294 (
2295 "dropped",
2296 json!(dropped
2297 .iter()
2298 .map(|(at, closer)| json!({"at": at, "char": closer.to_string()}))
2299 .collect::<Vec<_>>()),
2300 ),
2301 ],
2302 );
2303 notes.insert(call.id.clone(), repair_note(&dropped));
2304 call.arguments = arguments;
2305 }
2306 notes
2307 }
2308
2309 pub(crate) fn annotate_broken_json(
2314 &self,
2315 call: &ToolCall,
2316 result: ToolResult,
2317 repairs: &HashMap<String, String>,
2318 streak: &mut BrokenStreak,
2319 ) -> ToolResult {
2320 let mut result = result;
2321 if let Some(note) = repairs.get(&call.id) {
2322 append_note(&mut result, note);
2323 }
2324 if let Some(count) = streak.observe(call) {
2325 let mut advice = format!(
2326 "{count} calls in a row to {} have sent arguments that do not parse. Long, \
2327 deeply nested arguments break most often: send less in each call.",
2328 call.name
2329 );
2330 if let Some(hint) = self
2331 .registry
2332 .get(&call.name)
2333 .and_then(|tool| tool.retry_hint().map(str::to_owned))
2334 {
2335 advice.push(' ');
2336 advice.push_str(&hint);
2337 }
2338 append_note(&mut result, &advice);
2339 }
2340 result
2341 }
2342
2343 fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
2346 if self.guardrails.egress == EgressMode::Off {
2347 return;
2348 }
2349 for call in calls {
2350 let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
2351 let (report, _) = self.guardrails.inspect_egress(&payload);
2352 if report.flagged() {
2353 self.recorder.event(
2354 sid,
2355 "guardrail",
2356 vec![
2357 ("stage", json!("egress_tool_args")),
2358 ("tool", json!(call.name)),
2359 ("findings", json!(report.summary())),
2360 ],
2361 );
2362 }
2363 }
2364 }
2365
2366 async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
2368 match self.resolve_call(call, sid) {
2369 (Some(result), _) => (result, Usage::default()),
2370 (None, _) => self.dispatch_call(call, sid).await,
2371 }
2372 }
2373}
2374
2375#[derive(Debug, Default)]
2378pub(crate) struct BrokenStreak(HashMap<String, u32>);
2379
2380impl BrokenStreak {
2381 fn observe(&mut self, call: &ToolCall) -> Option<u32> {
2385 let count = self.0.entry(call.name.clone()).or_default();
2386 if call.invalid_arguments().is_none() {
2387 *count = 0;
2388 return None;
2389 }
2390 *count += 1;
2391 (*count >= 2).then_some(*count)
2392 }
2393}
2394
2395fn repair_note(dropped: &[(usize, char)]) -> String {
2397 let closers: Vec<String> = dropped
2398 .iter()
2399 .map(|(at, closer)| format!("`{closer}` at character {at}"))
2400 .collect();
2401 let noun = if dropped.len() == 1 {
2402 "closer"
2403 } else {
2404 "closers"
2405 };
2406 format!(
2407 "Note: these arguments were not valid JSON. agent86 dropped the unmatched {noun} {}, \
2408 which matched nothing, and ran the call with the rest. Check next time that every \
2409 bracket closes in order.",
2410 closers.join(", ")
2411 )
2412}
2413
2414fn append_note(result: &mut ToolResult, note: &str) {
2417 let text = if result.ok {
2418 &mut result.content
2419 } else {
2420 result.error.get_or_insert_with(String::new)
2421 };
2422 if !text.is_empty() {
2423 text.push_str("\n\n");
2424 }
2425 text.push_str(note);
2426}
2427
2428fn request_goal<'m>(
2432 messages: &'m [Message],
2433 goal: usize,
2434 note: Option<&str>,
2435) -> std::borrow::Cow<'m, [Message]> {
2436 match note {
2437 Some(note) if goal < messages.len() => {
2438 let mut sent = messages.to_vec();
2439 sent[goal].content = with_turn_note(&sent[goal].content, note);
2440 std::borrow::Cow::Owned(sent)
2441 }
2442 _ => std::borrow::Cow::Borrowed(messages),
2443 }
2444}
2445
2446fn answer_unrecorded(messages: &mut Vec<Message>, from: usize) -> usize {
2452 let mut answered = 0;
2453 let mut index = from;
2454 while index < messages.len() {
2455 if messages[index].role != Role::Assistant || messages[index].tool_calls.is_empty() {
2456 index += 1;
2457 continue;
2458 }
2459 let mut pending = messages[index].tool_calls.clone();
2460 let mut end = index + 1;
2461 while end < messages.len() && messages[end].role == Role::Tool {
2462 let id = messages[end].tool_call_id.as_deref();
2463 pending.retain(|call| Some(call.id.as_str()) != id);
2464 end += 1;
2465 }
2466 for call in pending {
2467 let result = ToolResult {
2468 error: Some(UNRECORDED_RESULT.to_owned()),
2469 ..not_executed(&call, "")
2470 };
2471 messages.insert(
2472 end,
2473 Message {
2474 tool_call_id: Some(call.id.clone()),
2475 name: Some(call.name.clone()),
2476 ..message(Role::Tool, &observation(&result))
2477 },
2478 );
2479 end += 1;
2480 answered += 1;
2481 }
2482 index = end;
2483 }
2484 answered
2485}
2486
2487pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
2489 ToolResult {
2490 call_id: call.id.clone(),
2491 name: call.name.clone(),
2492 ok: false,
2493 content: String::new(),
2494 error: Some(format!("Not executed: {reason}.")),
2495 metadata: serde_json::Map::new(),
2496 }
2497}
2498
2499fn model_call_attributes(
2501 completion: Option<&crate::types::Completion>,
2502) -> Vec<(&'static str, Value)> {
2503 let Some(completion) = completion else {
2504 return vec![("agent86.completed", json!(false))];
2505 };
2506 let finish = completion
2507 .stop_reason
2508 .as_deref()
2509 .filter(|reason| !reason.is_empty())
2510 .map_or(Value::Null, |reason| json!([reason]));
2511 vec![
2512 ("agent86.completed", json!(true)),
2513 (
2514 "gen_ai.usage.input_tokens",
2515 json!(completion.usage.input_tokens),
2516 ),
2517 (
2518 "gen_ai.usage.output_tokens",
2519 json!(completion.usage.output_tokens),
2520 ),
2521 ("gen_ai.response.finish_reasons", finish),
2522 ("agent86.cost_usd", json!(completion.usage.cost_usd)),
2523 ("agent86.tool_calls", json!(completion.tool_calls.len())),
2524 ]
2525}
2526
2527fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
2530 let mut attributes = vec![("gen_ai.request.model", json!(model))];
2531 if let Some(summary) = &state.last_turn {
2532 attributes.extend([
2533 ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
2534 ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
2535 ("agent86.cost_usd", json!(summary.cost_usd)),
2536 ("agent86.steps", json!(summary.steps)),
2537 ("agent86.tool_calls", json!(summary.tool_calls)),
2538 ("agent86.duration_s", json!(summary.duration_s)),
2539 (
2540 "agent86.phase",
2541 serde_json::to_value(state.phase).unwrap_or(Value::Null),
2542 ),
2543 ]);
2544 }
2545 attributes
2546}
2547
2548fn record_step(state: &mut AgentState, step: Step) {
2550 state.usage = state.usage + step.usage;
2551 state.steps.push(step);
2552}
2553
2554fn message(role: Role, content: &str) -> Message {
2555 Message {
2556 role,
2557 content: content.to_owned(),
2558 tool_calls: Vec::new(),
2559 tool_call_id: None,
2560 name: None,
2561 }
2562}
2563
2564pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
2570 let preview = truncate_chars(raw, 200);
2571 let mut error = format!(
2572 "invalid JSON in tool arguments: {} could not be parsed. \
2573 Call the tool again with its arguments as a single valid JSON object.",
2574 python_repr(&preview)
2575 );
2576 if let Some(location) = crate::broken_json::describe(raw) {
2577 error.push('\n');
2578 error.push_str(&location);
2579 }
2580 ToolResult {
2581 call_id: call.id.clone(),
2582 name: call.name.clone(),
2583 ok: false,
2584 content: String::new(),
2585 error: Some(error),
2586 metadata: serde_json::Map::new(),
2587 }
2588}
2589
2590pub fn observation(result: &ToolResult) -> String {
2593 if result.ok {
2594 return result.content.clone();
2595 }
2596 let error = result.error.as_deref().unwrap_or_default().trim();
2597 let body = result.content.trim();
2598 match (error.is_empty(), body.is_empty()) {
2599 (false, false) => format!("{error}\n{body}"),
2600 (false, true) => error.to_owned(),
2601 (true, false) => body.to_owned(),
2602 (true, true) => "error".to_owned(),
2603 }
2604}
2605
2606pub(crate) fn request_temperature(provider: &dyn Provider, specialty: Option<f32>) -> f32 {
2609 specialty.or_else(|| provider.temperature()).unwrap_or(0.0)
2610}
2611
2612pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
2614 let text = python_json_dumps(&Value::Object(arguments.clone()), false);
2615 truncate_chars(&text, 160)
2616}
2617
2618pub fn summarize(result: &ToolResult) -> String {
2620 if !result.ok {
2621 let error = result.error.as_deref().unwrap_or_default().trim();
2622 let content = result.content.trim();
2623 let detail = [error, content, "(failed)"]
2624 .into_iter()
2625 .find(|text| !text.is_empty())
2626 .unwrap_or("(failed)");
2627 return format!("error: {}", first_chars(first_line(detail), 160));
2628 }
2629 let content = result.content.trim();
2630 let head = if content.is_empty() {
2631 "(no output)"
2632 } else {
2633 first_line(content)
2634 };
2635 first_chars(head, 160)
2636}
2637
2638fn first_line(text: &str) -> &str {
2640 let is_break = |c: char| {
2641 matches!(
2642 c,
2643 '\n' | '\r'
2644 | '\u{b}'
2645 | '\u{c}'
2646 | '\u{1c}'
2647 | '\u{1d}'
2648 | '\u{1e}'
2649 | '\u{85}'
2650 | '\u{2028}'
2651 | '\u{2029}'
2652 )
2653 };
2654 text.split(is_break).next().unwrap_or_default()
2655}
2656
2657fn first_chars(text: &str, limit: usize) -> String {
2658 text.chars().take(limit).collect()
2659}
2660
2661fn truncate_chars(text: &str, limit: usize) -> String {
2663 if text.chars().count() <= limit {
2664 text.to_owned()
2665 } else {
2666 format!("{} ...", first_chars(text, limit))
2667 }
2668}
2669
2670#[cfg(test)]
2671mod tests {
2672 use super::*;
2673 use serde_json::json;
2674
2675 fn limits() -> LimitsConfig {
2676 LimitsConfig {
2677 max_steps: 2,
2678 max_cost_usd: 1.0,
2679 max_wall_clock_s: 900,
2680 max_consecutive_errors: 1,
2681 max_context_tokens: 0,
2682 max_output_tokens: 8192,
2683 context_reserve_tokens: 4096,
2684 compaction: CompactionMode::Summarize,
2685 parallel_tools: true,
2686 tool_timeout_s: 60,
2687 context_sizing: true,
2688 stall_nudge: true,
2689 }
2690 }
2691
2692 #[test]
2693 fn the_breaker_trips_on_steps_cost_and_error_streaks() {
2694 let mut breaker = CircuitBreaker::new(&limits());
2695 breaker.before_step().unwrap();
2696 breaker.record_step(&Usage::default());
2697 breaker.record_step(&Usage::default());
2698 assert_eq!(
2699 breaker.before_step().unwrap_err().to_string(),
2700 "Circuit tripped: step budget reached (2 steps)"
2701 );
2702
2703 let mut costly = CircuitBreaker::new(&limits());
2704 costly.record_step(&Usage {
2705 cost_usd: 1.25,
2706 ..Usage::default()
2707 });
2708 assert_eq!(
2709 costly.before_step().unwrap_err().to_string(),
2710 "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
2711 );
2712
2713 let mut errors = CircuitBreaker::new(&limits());
2714 errors.record_tool_result(false).unwrap();
2715 errors.record_tool_result(true).unwrap();
2716 errors.record_tool_result(false).unwrap();
2717 assert_eq!(
2718 errors.record_tool_result(false).unwrap_err().to_string(),
2719 "Circuit tripped: aborted after 2 consecutive tool errors"
2720 );
2721 }
2722
2723 fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
2724 ToolResult {
2725 call_id: "c".to_owned(),
2726 name: "t".to_owned(),
2727 ok,
2728 content: content.to_owned(),
2729 error: error.map(str::to_owned),
2730 metadata: serde_json::Map::new(),
2731 }
2732 }
2733
2734 #[test]
2735 fn observations_keep_both_error_and_output() {
2736 assert_eq!(observation(&result(true, "data", None)), "data");
2737 assert_eq!(
2738 observation(&result(false, " out ", Some(" bad "))),
2739 "bad\nout"
2740 );
2741 assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
2742 assert_eq!(observation(&result(false, "", None)), "error");
2743 }
2744
2745 #[test]
2746 fn summaries_show_the_first_line() {
2747 assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
2748 assert_eq!(summarize(&result(true, " ", None)), "(no output)");
2749 assert_eq!(
2750 summarize(&result(false, "", Some("No such file: x\nmore"))),
2751 "error: No such file: x"
2752 );
2753 assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
2754 assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
2755 }
2756
2757 #[test]
2758 fn previews_use_python_json_and_cut_at_160_characters() {
2759 let Value::Object(short) = json!({"path": "src/main.rs"}) else {
2760 unreachable!()
2761 };
2762 assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
2763
2764 let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
2765 unreachable!()
2766 };
2767 let preview = preview_arguments(&long);
2768 assert!(preview.ends_with(" ..."));
2769 assert_eq!(preview.chars().count(), 164);
2770 }
2771
2772 #[test]
2773 fn invalid_json_is_reported_with_a_python_repr_preview() {
2774 let call = ToolCall {
2775 id: "c1".to_owned(),
2776 name: "read_file".to_owned(),
2777 arguments: serde_json::Map::new(),
2778 };
2779 let result = invalid_arguments_result(&call, "{\"path\": ");
2780 let error = result.error.as_deref().unwrap();
2781 assert_eq!(
2783 error.lines().next(),
2784 Some(
2785 "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
2786 Call the tool again with its arguments as a single valid JSON object."
2787 )
2788 );
2789 assert_eq!(
2790 error.lines().nth(1),
2791 Some(
2792 "The JSON ends at character 9 inside the top-level object, before it is \
2793 complete: EOF while parsing a value."
2794 )
2795 );
2796 assert!(!result.ok);
2797 assert_eq!(result.call_id, "c1");
2798 }
2799}