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::working::{
30 apply_summary, compacted_notice, compaction_cut, compaction_failed_notice, conversation_budget,
31 count_spec_tokens, count_tokens, fit, fits, python_strip, render_transcript, KEEP_RECENT,
32 SUMMARY_MAX_TOKENS, SUMMARY_SYSTEM_PROMPT,
33};
34use crate::observability::Recorder;
35use crate::prompt::time_note;
36use crate::provider::reasoning::REASONING_LOOP;
37use crate::provider::{Provider, ProviderError};
38use crate::pyjson::{python_float_repr, python_json_dumps};
39use crate::router::Router;
40use crate::session::AgentState;
41use crate::tools::{ToolContext, ToolRegistry};
42use crate::turn::TurnSummary;
43use crate::types::{
44 python_repr, AgentPhase, CompletionRequest, Message, Role, Step, ToolCall, ToolResult,
45 ToolSpec, Usage,
46};
47use crate::vault::StreamRedactor;
48use futures_util::StreamExt;
49use serde_json::{json, Value};
50use std::sync::atomic::{AtomicBool, Ordering};
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53use thiserror::Error;
54
55pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
57
58pub const MAX_CONTINUATIONS: u64 = 3;
60
61pub fn continuation_notice(index: u64) -> String {
63 format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
64}
65
66pub const ANSWER_PROMPT: &str =
68 "Your last reply was empty. Give the user your answer now, as plain text.";
69
70pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
72
73pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
75
76pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
78
79pub const REASONING_LOOP_NOTICE: &str =
82 "\n[the model's reasoning was repeating itself; stopped it]\n";
83
84pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
86
87#[derive(Clone, Default)]
92pub struct CancelToken {
93 inner: Arc<CancelInner>,
94}
95
96impl std::fmt::Debug for CancelToken {
97 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 formatter
99 .debug_struct("CancelToken")
100 .field("cancelled", &self.is_cancelled())
101 .finish()
102 }
103}
104
105#[derive(Default)]
106struct CancelInner {
107 flag: AtomicBool,
108 notify: tokio::sync::Notify,
109}
110
111impl CancelToken {
112 pub fn cancel(&self) {
113 self.inner.flag.store(true, Ordering::SeqCst);
114 self.inner.notify.notify_waiters();
115 }
116
117 pub fn is_cancelled(&self) -> bool {
118 self.inner.flag.load(Ordering::SeqCst)
119 }
120
121 pub fn clear(&self) {
122 self.inner.flag.store(false, Ordering::SeqCst);
123 }
124
125 pub async fn cancelled(&self) {
127 loop {
128 let notified = self.inner.notify.notified();
129 tokio::pin!(notified);
130 notified.as_mut().enable();
132 if self.is_cancelled() {
133 return;
134 }
135 notified.await;
136 }
137 }
138}
139
140#[derive(Debug, Clone, Copy)]
147#[non_exhaustive]
148pub enum TurnEvent<'a> {
149 Text(&'a str),
151 Notice(&'a str),
155 Thinking(&'a str),
158 ToolCall { call: &'a ToolCall, text: &'a str },
160 ToolResult {
163 call: &'a ToolCall,
164 result: &'a ToolResult,
165 observation: &'a str,
166 text: &'a str,
167 },
168 Usage {
172 step: &'a crate::types::Usage,
173 session: &'a crate::types::Usage,
174 },
175 Compacted {
180 notice: &'a str,
181 summary: Option<&'a str>,
182 },
183 #[cfg(feature = "agent86ui")]
187 Ui(&'a agent86_ui::AgentMessage),
188}
189
190impl<'a> TurnEvent<'a> {
191 pub fn text(&self) -> &'a str {
193 match *self {
194 Self::Text(text)
195 | Self::Notice(text)
196 | Self::ToolCall { text, .. }
197 | Self::ToolResult { text, .. }
198 | Self::Compacted { notice: text, .. } => text,
199 Self::Thinking(_) | Self::Usage { .. } => "",
200 #[cfg(feature = "agent86ui")]
201 Self::Ui(_) => "",
202 }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq, Error)]
208pub enum HarnessError {
209 #[error(transparent)]
210 Provider(#[from] ProviderError),
211
212 #[error("Circuit tripped: {0}")]
213 CircuitTripped(String),
214
215 #[error(
216 "The '{provider}' provider ended its stream for model {} without a final completion. \
217 The response was truncated; retry, or check the endpoint's streaming implementation.",
218 python_repr(model)
219 )]
220 NoFinalCompletion { provider: String, model: String },
221}
222
223impl HarnessError {
224 pub fn python_type(&self) -> &'static str {
227 match self {
228 Self::Provider(_) => "ProviderError",
229 Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
230 }
231 }
232}
233
234pub struct CircuitBreaker {
236 limits: LimitsConfig,
237 steps: u32,
238 cost_usd: f64,
239 consecutive_errors: u32,
240 started: Instant,
241}
242
243impl CircuitBreaker {
244 pub fn new(limits: &LimitsConfig) -> Self {
245 Self {
246 limits: limits.clone(),
247 steps: 0,
248 cost_usd: 0.0,
249 consecutive_errors: 0,
250 started: Instant::now(),
251 }
252 }
253
254 pub fn steps(&self) -> u32 {
255 self.steps
256 }
257
258 pub fn max_steps(&self) -> u32 {
260 self.limits.max_steps
261 }
262
263 pub fn set_max_steps(&mut self, max_steps: u32) {
265 self.limits.max_steps = max_steps;
266 }
267
268 pub fn out_of_steps(&self) -> bool {
270 self.steps >= self.limits.max_steps
271 }
272
273 pub fn before_step(&self) -> Result<(), HarnessError> {
275 let limits = &self.limits;
276 if self.steps >= limits.max_steps {
277 return Err(trip(format!(
278 "step budget reached ({} steps)",
279 limits.max_steps
280 )));
281 }
282 if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
283 return Err(trip(format!(
284 "cost cap reached (${:.4} >= ${})",
285 self.cost_usd,
286 python_float_repr(limits.max_cost_usd)
287 )));
288 }
289 let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
290 if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
291 return Err(trip(format!(
292 "wall-clock limit reached ({}s)",
293 limits.max_wall_clock_s
294 )));
295 }
296 Ok(())
297 }
298
299 pub fn record_step(&mut self, usage: &Usage) {
300 self.steps += 1;
301 self.cost_usd += usage.cost_usd;
302 }
303
304 pub fn cost(&self) -> f64 {
307 self.cost_usd
308 }
309
310 pub fn record_cost(&mut self, cost_usd: f64) {
311 self.cost_usd += cost_usd;
312 }
313
314 pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
315 if ok {
316 self.consecutive_errors = 0;
317 return Ok(());
318 }
319 self.consecutive_errors += 1;
320 if self.consecutive_errors > self.limits.max_consecutive_errors {
321 return Err(trip(format!(
322 "aborted after {} consecutive tool errors",
323 self.consecutive_errors
324 )));
325 }
326 Ok(())
327 }
328}
329
330fn trip(reason: String) -> HarnessError {
331 HarnessError::CircuitTripped(reason)
332}
333
334pub struct Harness {
336 pub provider: Arc<dyn Provider>,
339 pub router: Router,
341 pub tracer: crate::otel::Tracer,
343 pub registry: ToolRegistry,
344 pub context: ToolContext,
345 pub limits: LimitsConfig,
346 pub agents: AgentsConfig,
348 pub system: Message,
349 pub max_tokens: u32,
352 pub session_limits: crate::limits::SessionLimits,
355 pub context_window: u64,
358 pub gate: ApprovalGate,
360 pub guardrails: Guardrails,
362 pub recorder: Recorder,
364 pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
367 pub memory: Option<crate::session::SessionStore>,
370 pub cancel: CancelToken,
372 pub subagents: crate::subagent::SubagentState,
375}
376
377impl Harness {
378 pub(crate) fn system_message(&self, extra: Option<&str>) -> Message {
383 let offered = self.delegation_offered(&self.context, 0);
384 if let Some((persona, preloaded)) = self.subagents.main() {
386 return self.filtered_system(&persona, &self.context, &preloaded, offered, extra);
387 }
388 self.system_for(&self.context, offered, extra)
389 }
390
391 pub(crate) fn system_for(
395 &self,
396 ctx: &ToolContext,
397 delegation_offered: bool,
398 extra: Option<&str>,
399 ) -> Message {
400 let mut system = self.system.clone();
401 if let Some(section) = self
402 .mcp
403 .as_ref()
404 .map(|mcp| mcp.prompt_section())
405 .filter(|section| !section.is_empty())
406 {
407 system.content = format!("{}\n\n{section}", system.content);
408 }
409 if delegation_offered {
410 if let Some(section) = self.specialty_listing(ctx) {
411 system.content = format!("{}\n\n{section}", system.content);
412 }
413 }
414 if let Some(section) = ctx.secrets.prompt_section() {
415 system.content = format!("{}\n\n{section}", system.content);
416 }
417 #[cfg(feature = "agent86ui")]
420 if let Some(ui) = ctx.ui.as_deref() {
421 if ctx.allowed_tool(crate::agent86ui::RENDER_UI) {
422 system.content = format!("{}\n\n{}", system.content, ui.prompt_section());
423 }
424 }
425 if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
426 system.content = format!("{}\n\n{extra}", system.content);
427 }
428 system
429 }
430
431 pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
436 self.context_budget_with(
437 system,
438 specs,
439 self.active_context_window(),
440 self.output_cap(),
441 )
442 }
443
444 pub(crate) fn context_budget_with(
447 &self,
448 system: &Message,
449 specs: &[ToolSpec],
450 window: u64,
451 output_cap: u32,
452 ) -> u64 {
453 let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
454 conversation_budget(
455 window,
456 overhead,
457 self.limits.context_reserve_tokens,
458 u64::from(output_cap),
459 self.limits.max_context_tokens,
460 )
461 }
462
463 async fn compact_if_needed(
473 &self,
474 state: &mut AgentState,
475 extra_system: Option<&str>,
476 summary: &mut TurnSummary,
477 breaker: &mut CircuitBreaker,
478 protect_from: usize,
479 ) -> Option<(String, usize, Option<String>)> {
480 if self.limits.compaction != CompactionMode::Summarize {
481 return None;
482 }
483 let system = self.system_message(extra_system);
484 let budget = self.context_budget(&system, &self.registry.specs());
485 if fits(&state.messages, budget) {
486 return None;
487 }
488 let cut = compaction_cut(&state.messages, budget, KEEP_RECENT, Some(protect_from));
489 if cut == 0 {
490 return None;
493 }
494 let sid = state.session_id.clone();
495 let prefix = &state.messages[..cut];
496 let dropped_tokens = count_tokens(prefix);
497 let summarizer = self.summary_provider();
498 let request = CompletionRequest {
499 model: summarizer.model().to_owned(),
500 messages: vec![
501 message(Role::System, SUMMARY_SYSTEM_PROMPT),
502 message(Role::User, &render_transcript(prefix)),
503 ],
504 tools: Vec::new(),
505 temperature: 0.0,
506 max_tokens: Some(SUMMARY_MAX_TOKENS * 2),
508 stream: false,
509 };
510 let completion = tokio::select! {
511 biased;
512 () = self.cancel.cancelled() => return None,
514 completion = summarizer.complete(request) => completion,
515 };
516 let failed = |status: &str, error: Option<String>| {
517 let mut fields = vec![
518 ("status", json!(status)),
519 ("fallback", json!("drop")),
520 ("dropped", json!(cut)),
521 ];
522 if let Some(error) = error {
523 fields.push(("error", json!(error)));
524 }
525 self.recorder.event(&sid, "compaction", fields);
526 Some((compaction_failed_notice(cut), 0, None))
527 };
528 let completion = match completion {
529 Ok(completion) => completion,
530 Err(error) => return failed("failed", Some(format!("ProviderError: {error}"))),
531 };
532 let text = python_strip(&completion.text).to_owned();
533 if text.is_empty() {
534 return failed("empty", None);
535 }
536
537 if let Some(memory) = &self.memory {
539 let _ = memory.record_compaction(&sid, &text, prefix);
540 }
541 let before = state.messages.len();
542 let kept = state.messages.split_off(cut);
543 state.messages = apply_summary(&text, kept);
544 summary.compactions += 1;
545 summary.add_usage(&completion.usage);
546 breaker.record_cost(completion.usage.cost_usd);
547 self.recorder.event(
548 &sid,
549 "compaction",
550 vec![
551 ("status", json!("ok")),
552 ("dropped", json!(cut)),
553 ("dropped_tokens", json!(dropped_tokens)),
554 (
555 "summary_tokens",
556 json!(count_tokens(&[message(Role::User, &text)])),
557 ),
558 ("kept", json!(state.messages.len())),
559 ("model", json!(summarizer.model())),
560 ],
561 );
562 if let Some(memory) = &self.memory {
565 let _ = memory.persist(state);
566 }
567 Some((
568 compacted_notice(cut),
569 before - state.messages.len(),
570 Some(text),
571 ))
572 }
573
574 pub async fn run_turn(
581 &self,
582 state: &mut AgentState,
583 goal: &str,
584 on_text: impl FnMut(&str),
585 ) -> Result<String, HarnessError> {
586 self.run_turn_as(state, goal, goal, on_text).await
587 }
588
589 pub async fn run_turn_as(
593 &self,
594 state: &mut AgentState,
595 user_text: &str,
596 display_text: &str,
597 mut on_text: impl FnMut(&str),
598 ) -> Result<String, HarnessError> {
599 self.run_turn_events(state, user_text, display_text, |event| {
600 on_text(event.text())
601 })
602 .await
603 }
604
605 pub async fn run_turn_events(
609 &self,
610 state: &mut AgentState,
611 user_text: &str,
612 display_text: &str,
613 on_event: impl FnMut(TurnEvent<'_>),
614 ) -> Result<String, HarnessError> {
615 self.run_turn_with(state, user_text, display_text, None, on_event)
616 .await
617 }
618
619 pub async fn run_skill_turn(
626 &self,
627 state: &mut AgentState,
628 skill: &Arc<crate::skills::Skill>,
629 task: &str,
630 display_text: &str,
631 on_event: impl FnMut(TurnEvent<'_>),
632 ) -> Result<String, HarnessError> {
633 let user_text = crate::skills::skill_request(skill, task);
634 self.run_turn_with(state, &user_text, display_text, Some(skill), on_event)
635 .await
636 }
637
638 async fn run_turn_with(
639 &self,
640 state: &mut AgentState,
641 user_text: &str,
642 display_text: &str,
643 skill: Option<&Arc<crate::skills::Skill>>,
644 on_event: impl FnMut(TurnEvent<'_>),
645 ) -> Result<String, HarnessError> {
646 self.cancel.clear();
648 self.context.clear_skill();
653 if let Some(skill) = skill {
654 self.context.activate_skill(skill);
655 }
656 let started = Instant::now();
657 let mut span = self.tracer.start(
659 "turn",
660 vec![
661 ("session.id", json!(state.session_id)),
662 (
663 "gen_ai.request.model",
664 json!(self.active_provider().model()),
665 ),
666 ],
667 );
668 let mut summary = TurnSummary::default();
669 let secrets = &self.context.secrets;
672 let (user_text, display_text) = (secrets.redact(user_text), secrets.redact(display_text));
673 let result = self
674 .turn(state, &user_text, &display_text, &mut summary, on_event)
675 .await;
676 self.context.clear_skill();
677 summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
678 state.last_turn = Some(summary);
679 if let Err(error) = &result {
680 state.phase = AgentPhase::Error;
681 let reason = match error {
682 HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
683 HarnessError::Provider(detail) => {
684 format!("provider stream failed: ProviderError: {detail}")
685 }
686 HarnessError::NoFinalCompletion { .. } => {
687 "provider stream ended without a final completion".to_owned()
688 }
689 };
690 self.recorder.event(
691 &state.session_id,
692 "turn_end",
693 vec![("status", json!("error")), ("reason", json!(reason))],
694 );
695 }
696 span.set(turn_attributes(state, self.active_provider().model()));
699 if let Err(error) = &result {
700 span.fail(error.python_type(), &error.to_string());
701 }
702 self.tracer.end(span);
703 result
704 }
705
706 async fn turn(
707 &self,
708 state: &mut AgentState,
709 goal: &str,
710 display_text: &str,
711 summary: &mut TurnSummary,
712 mut on_event: impl FnMut(TurnEvent<'_>),
713 ) -> Result<String, HarnessError> {
714 let mut output = String::new();
715 let mut emit = |event: TurnEvent<'_>| {
716 output.push_str(event.text());
717 on_event(event);
718 };
719
720 let sid = state.session_id.clone();
721 self.recorder
722 .event(&sid, "turn_start", vec![("task", json!(display_text))]);
723
724 let report = self.guardrails.inspect_ingress(goal);
726 if report.flagged() {
727 self.recorder.event(
728 &sid,
729 "guardrail",
730 vec![
731 ("stage", json!("ingress_input")),
732 ("findings", json!(report.summary())),
733 ],
734 );
735 if self.guardrails.should_block(&report) {
736 let refusal = format!(
737 "Refused: input tripped the ingress guardrail ({}).",
738 report.summary()
739 );
740 state.messages.push(message(Role::User, goal));
741 state.messages.push(message(Role::Assistant, &refusal));
742 state.phase = AgentPhase::Error;
743 self.recorder
744 .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
745 emit(TurnEvent::Text(&refusal));
746 return Ok(output);
747 }
748 emit(TurnEvent::Notice(&format!(
749 "[guardrail] input flagged: {}\n",
750 report.summary()
751 )));
752 }
753
754 let buffering = self.guardrails.egress == EgressMode::Redact;
757
758 self.route(goal, &sid)?;
760 let provider = self.active_provider();
761
762 let recall_note = self
764 .memory
765 .as_ref()
766 .and_then(|memory| memory.recall_note(goal));
767 let time = time_note(&jiff::ZonedDateTime::now());
769 let recall_note = Some(match recall_note {
770 Some(recalled) => format!("{time}\n\n{recalled}"),
771 None => time,
772 });
773 let mut turn_start = state.messages.len();
776 state.messages.push(message(Role::User, goal));
777 let mut limits = self.limits.clone();
778 limits.max_steps = self.max_steps();
779 let mut breaker = CircuitBreaker::new(&limits);
780 let mut continuation_start: Option<usize> = None;
782 let mut continuation_parts: Vec<String> = Vec::new();
783 let mut nudged = false;
787 let mut ask_again = false;
788 let mut unanswered_thinking = String::new();
789
790 loop {
791 if self.cancel.is_cancelled() {
794 self.cancelled(state, breaker.steps(), &mut emit);
795 return Ok(output);
796 }
797 if breaker.out_of_steps() {
799 match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
800 Some(raised) => breaker.set_max_steps(raised),
801 None if self.cancel.is_cancelled() => {
803 self.cancelled(state, breaker.steps(), &mut emit);
804 return Ok(output);
805 }
806 None => {}
807 }
808 }
809 breaker.before_step()?;
810
811 if let Some((notice, removed, compacted)) = self
814 .compact_if_needed(
815 state,
816 recall_note.as_deref(),
817 summary,
818 &mut breaker,
819 turn_start,
820 )
821 .await
822 {
823 turn_start -= removed;
826 if let Some(start) = continuation_start.as_mut() {
827 *start -= removed;
828 }
829 emit(TurnEvent::Compacted {
832 notice: ¬ice,
833 summary: compacted.as_deref(),
834 });
835 }
836
837 let mut completion = {
838 let system = self.system_message(recall_note.as_deref());
839 let mut tools = self.registry.specs();
840 tools.retain(|spec| self.context.scope_allows(&spec.name));
842 let budget = self.context_budget(&system, &tools);
843 let conversation = fit(&state.messages, budget);
844 let mut request_messages = Vec::with_capacity(conversation.len() + 1);
845 request_messages.push(system);
846 request_messages.extend(conversation.iter().cloned());
847 if std::mem::take(&mut ask_again) {
848 request_messages.push(message(Role::User, ANSWER_PROMPT));
849 }
850 let request = CompletionRequest {
851 model: provider.model().to_owned(),
852 messages: request_messages,
853 tools,
854 temperature: 0.0,
855 max_tokens: Some(self.output_cap()),
856 stream: true,
857 };
858 let mut span = self.tracer.start(
860 "model_call",
861 vec![
862 ("gen_ai.system", json!(provider.name())),
863 ("gen_ai.request.model", json!(provider.model())),
864 ("agent86.step", json!(breaker.steps() + 1)),
865 ],
866 );
867 let mut stream = provider.stream(request);
868 let mut completion = None;
869 let mut buffered = String::new();
870 let mut redactor = StreamRedactor::default();
873 let mut thinking_redactor = StreamRedactor::default();
874 loop {
875 let next = tokio::select! {
878 biased;
879 () = self.cancel.cancelled() => None,
880 delta = stream.next() => Some(delta),
881 };
882 let Some(Some(delta)) = next else { break };
883 let delta = match delta {
884 Ok(delta) => delta,
885 Err(error) => {
886 span.set(model_call_attributes(None));
887 span.fail("ProviderError", &error.to_string());
888 self.tracer.end(span);
889 return Err(error.into());
890 }
891 };
892 if !delta.thinking.is_empty() && !buffering {
895 let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
896 if !shown.is_empty() {
897 emit(TurnEvent::Thinking(&shown));
898 }
899 }
900 if !delta.text.is_empty() {
901 if buffering {
902 buffered.push_str(&delta.text);
903 } else {
904 let shown = redactor.push(&self.context.secrets, &delta.text);
905 if !shown.is_empty() {
906 emit(TurnEvent::Text(&shown));
907 }
908 }
909 }
910 if delta.done && delta.completion.is_some() {
911 completion = delta.completion;
912 }
913 }
914 drop(stream);
915 let held = thinking_redactor.finish(&self.context.secrets);
916 if !held.is_empty() {
917 emit(TurnEvent::Thinking(&held));
918 }
919 let held = redactor.finish(&self.context.secrets);
920 if !held.is_empty() {
921 emit(TurnEvent::Text(&held));
922 }
923 span.set(model_call_attributes(completion.as_ref()));
924 self.tracer.end(span);
925 if self.cancel.is_cancelled() {
926 let partial = self
928 .guardrails
929 .inspect_egress(&self.context.secrets.redact(&buffered))
930 .1;
931 if !partial.is_empty() {
932 emit(TurnEvent::Text(&partial));
933 }
934 self.cancelled(state, breaker.steps(), &mut emit);
935 return Ok(output);
936 }
937 completion.ok_or_else(|| HarnessError::NoFinalCompletion {
938 provider: provider.name().to_owned(),
939 model: provider.model().to_owned(),
940 })?
941 };
942
943 breaker.record_step(&completion.usage);
944 summary.steps = u64::from(breaker.steps());
945 summary.add_usage(&completion.usage);
946 emit(TurnEvent::Usage {
949 step: &completion.usage,
950 session: &(state.usage + completion.usage),
951 });
952 let names: Vec<&str> = completion
953 .tool_calls
954 .iter()
955 .map(|call| call.name.as_str())
956 .collect();
957 self.recorder.event(
958 &sid,
959 "model_call",
960 vec![
961 ("step", json!(breaker.steps())),
962 ("model", json!(provider.model())),
963 ("input_tokens", json!(completion.usage.input_tokens)),
964 ("output_tokens", json!(completion.usage.output_tokens)),
965 ("cost_usd", json!(completion.usage.cost_usd)),
966 ("stop_reason", json!(completion.stop_reason)),
967 ("tool_calls", json!(names)),
968 ],
969 );
970
971 if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
972 emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
973 }
974 let stopped = completion
977 .stop_reason
978 .as_deref()
979 .and_then(|reason| reason.strip_prefix(crate::provider::google::STOPPED_PREFIX))
980 .map(str::to_owned);
981 if let Some(reason) = &stopped {
982 emit(TurnEvent::Notice(&format!(
983 "\n[{} stopped the reply: {reason}]\n",
984 provider.name()
985 )));
986 }
987
988 let mut from_thinking = false;
994 if completion.tool_calls.is_empty()
995 && completion.stop_reason.as_deref() != Some("max_tokens")
996 && stopped.is_none()
997 && completion.text.trim().is_empty()
998 && continuation_start.is_none()
999 {
1000 if !completion.thinking.trim().is_empty() {
1001 unanswered_thinking = std::mem::take(&mut completion.thinking);
1002 }
1003 if !nudged && !breaker.out_of_steps() {
1004 nudged = true;
1005 ask_again = true;
1006 self.recorder.event(
1007 &sid,
1008 "empty_answer",
1009 vec![
1010 ("step", json!(breaker.steps())),
1011 ("model", json!(provider.model())),
1012 ("thinking_chars", json!(unanswered_thinking.chars().count())),
1013 ],
1014 );
1015 record_step(
1016 state,
1017 Step {
1018 index: state.steps.len() as u64 + 1,
1019 phase: AgentPhase::Execute,
1020 thought: String::new(),
1021 tool_calls: Vec::new(),
1022 results: Vec::new(),
1023 usage: completion.usage,
1024 },
1025 );
1026 self.checkpoint(state);
1027 emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1028 continue;
1029 }
1030 if unanswered_thinking.trim().is_empty() {
1031 emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1032 if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1035 emit(TurnEvent::Notice(&format!(
1036 "{}\n",
1037 crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1038 )));
1039 }
1040 } else {
1041 completion.text = std::mem::take(&mut unanswered_thinking);
1042 from_thinking = true;
1043 emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1044 }
1045 }
1046
1047 let answer = self.context.secrets.redact(&completion.text);
1050 let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1051 let text = if buffering {
1052 if !redacted.is_empty() {
1053 emit(TurnEvent::Text(&redacted));
1054 }
1055 redacted
1056 } else {
1057 if from_thinking {
1059 emit(TurnEvent::Text(&answer));
1060 }
1061 answer
1062 };
1063 if egress.flagged() {
1064 self.recorder.event(
1065 &sid,
1066 "guardrail",
1067 vec![
1068 ("stage", json!("egress")),
1069 ("findings", json!(egress.summary())),
1070 ],
1071 );
1072 emit(TurnEvent::Notice(&format!(
1073 "\n[guardrail] output flagged: {}\n",
1074 egress.summary()
1075 )));
1076 }
1077 let tool_calls = completion.tool_calls;
1078 self.scan_tool_arguments(&tool_calls, &sid);
1079 let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1080 if cut_off
1085 && tool_calls.is_empty()
1086 && text.trim().is_empty()
1087 && continuation_start.is_none()
1088 {
1089 let cap = self.output_cap();
1090 if self
1091 .raise_limit(LimitKind::Output, None, &sid, cap, false)
1092 .is_some()
1093 {
1094 record_step(
1095 state,
1096 Step {
1097 index: state.steps.len() as u64 + 1,
1098 phase: AgentPhase::Execute,
1099 thought: String::new(),
1100 tool_calls: Vec::new(),
1101 results: Vec::new(),
1102 usage: completion.usage,
1103 },
1104 );
1105 self.checkpoint(state);
1106 continue;
1107 }
1108 }
1109 let mut step = Step {
1110 index: state.steps.len() as u64 + 1,
1111 phase: AgentPhase::Execute,
1112 thought: text.clone(),
1113 tool_calls: tool_calls.clone(),
1114 results: Vec::new(),
1115 usage: completion.usage,
1116 };
1117 state.messages.push(Message {
1118 tool_calls: tool_calls.clone(),
1119 ..message(Role::Assistant, &text)
1120 });
1121
1122 if tool_calls.is_empty() {
1123 if cut_off && summary.continuations < MAX_CONTINUATIONS {
1124 summary.continuations += 1;
1125 continuation_start.get_or_insert(state.messages.len() - 1);
1126 continuation_parts.push(text);
1127 state.messages.push(message(Role::User, CONTINUE_PROMPT));
1128 record_step(state, step);
1129 self.checkpoint(state);
1130 self.recorder.event(
1131 &sid,
1132 "continuation",
1133 vec![
1134 ("index", json!(summary.continuations)),
1135 ("step", json!(breaker.steps())),
1136 ("model", json!(provider.model())),
1137 (
1138 "chars",
1139 json!(continuation_parts
1140 .last()
1141 .map_or(0, |part| part.chars().count())),
1142 ),
1143 ],
1144 );
1145 emit(TurnEvent::Notice(&continuation_notice(
1146 summary.continuations,
1147 )));
1148 continue;
1149 }
1150 if let Some(start) = continuation_start {
1151 continuation_parts.push(text);
1153 let joined = continuation_parts.concat();
1154 state.messages.truncate(start);
1155 state.messages.push(message(Role::Assistant, &joined));
1156 step.thought = joined;
1157 }
1158 let outcome = step.thought.clone();
1159 record_step(state, step);
1160 state.phase = AgentPhase::Done;
1161 self.recorder.event(
1162 &sid,
1163 "turn_end",
1164 vec![
1165 ("status", json!("done")),
1166 ("steps", json!(breaker.steps())),
1167 ("continuations", json!(summary.continuations)),
1168 ],
1169 );
1170 if let Some(memory) = &self.memory {
1171 let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1173 }
1174 return Ok(output);
1175 }
1176
1177 continuation_start = None;
1179 continuation_parts.clear();
1180
1181 if self.cancel.is_cancelled() {
1185 for call in &tool_calls {
1186 let result = not_executed(call, "cancelled");
1187 state.messages.push(Message {
1188 tool_call_id: Some(call.id.clone()),
1189 name: Some(call.name.clone()),
1190 ..message(Role::Tool, &observation(&result))
1191 });
1192 step.results.push(result);
1193 }
1194 record_step(state, step);
1195 self.cancelled(state, breaker.steps(), &mut emit);
1196 return Ok(output);
1197 }
1198
1199 for call in &tool_calls {
1201 let text = format!(
1202 "\n[tool] {}({})\n",
1203 call.name,
1204 preview_arguments(&call.arguments)
1205 );
1206 emit(TurnEvent::ToolCall { call, text: &text });
1207 }
1208 let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1209 for notice in self.take_notices() {
1213 emit(TurnEvent::Notice(&format!("{notice}\n")));
1214 }
1215 for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1216 summary.tool_calls += 1;
1217 #[cfg(feature = "agent86ui")]
1220 let result = {
1221 let mut result = result;
1222 let (drawn, trace) = crate::agent86ui::take_drawn(&mut result.metadata);
1223 for message in &drawn {
1224 emit(TurnEvent::Ui(message));
1225 }
1226 if let Some(Value::Object(fields)) = trace {
1227 let fields: Vec<(&str, Value)> = fields
1230 .iter()
1231 .map(|(key, value)| (key.as_str(), value.clone()))
1232 .collect();
1233 self.recorder.event(&sid, "ui_render", fields);
1234 }
1235 match crate::agent86ui::take_wait(&mut result.metadata) {
1238 Some(surfaces) => self.ui_wait(call, result, surfaces, &sid),
1239 None => result,
1240 }
1241 };
1242 summary.add_usage(&delegated);
1245 step.usage = step.usage + delegated;
1246 breaker.record_cost(delegated.cost_usd);
1247 let (content, findings) = self.guardrails.observe(observation(&result));
1248 if let Some(findings) = findings {
1249 self.recorder.event(
1250 &sid,
1251 "guardrail",
1252 vec![
1253 ("stage", json!("observation")),
1254 ("tool", json!(call.name)),
1255 ("findings", json!(findings)),
1256 ],
1257 );
1258 }
1259 emit(TurnEvent::ToolResult {
1260 call,
1261 result: &result,
1262 observation: &content,
1263 text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1264 });
1265 state.messages.push(Message {
1266 tool_call_id: Some(call.id.clone()),
1267 name: Some(call.name.clone()),
1268 ..message(Role::Tool, &content)
1269 });
1270 let ok = result.ok;
1271 step.results.push(result);
1272 if let Err(tripped) = breaker.record_tool_result(ok) {
1273 record_step(state, step);
1274 return Err(tripped);
1275 }
1276 }
1277 record_step(state, step);
1280 self.checkpoint(state);
1281 if self.cancel.is_cancelled() {
1282 self.cancelled(state, breaker.steps(), &mut emit);
1283 return Ok(output);
1284 }
1285 }
1286 }
1287
1288 fn checkpoint(&self, state: &mut AgentState) {
1295 state.phase = AgentPhase::Execute;
1296 if let Some(memory) = &self.memory {
1297 let _ = memory.persist(state);
1298 }
1299 }
1300
1301 fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
1305 state.phase = AgentPhase::Error;
1306 self.recorder.event(
1307 &state.session_id,
1308 "turn_end",
1309 vec![
1310 ("status", json!("cancelled")),
1311 ("reason", json!("cancelled")),
1312 ("steps", json!(steps)),
1313 ],
1314 );
1315 emit(TurnEvent::Notice(CANCELLED_NOTICE));
1316 }
1317
1318 async fn execute_batch(
1332 &self,
1333 calls: &[ToolCall],
1334 sid: &str,
1335 spent: f64,
1336 ) -> Vec<(ToolResult, Usage)> {
1337 let eligible = calls
1338 .iter()
1339 .filter(|call| self.parallel_eligible(call))
1340 .count();
1341 let specialty: Vec<bool> = calls
1342 .iter()
1343 .map(|call| self.is_specialty_delegation(call))
1344 .collect();
1345 let any_specialty = specialty.contains(&true);
1346 if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
1347 let mut results = Vec::with_capacity(calls.len());
1349 for call in calls {
1350 results.push(if self.cancel.is_cancelled() {
1351 (not_executed(call, "cancelled"), Usage::default())
1352 } else {
1353 self.execute_tool(call, sid).await
1354 });
1355 }
1356 return results;
1357 }
1358
1359 let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
1360 let mut may_parallel = Vec::with_capacity(calls.len());
1361 for call in calls {
1362 let (result, parallel) = self.resolve_call(call);
1363 settled.push(result.map(|result| (result, Usage::default())));
1364 may_parallel.push(parallel);
1365 }
1366 let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
1367 let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
1368 let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
1369
1370 if reads.len() > 1 {
1371 let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
1372 let handles: Vec<_> = reads
1373 .iter()
1374 .map(|&index| {
1375 (
1376 index,
1377 scope.spawn(move || self.dispatch(&calls[index], sid)),
1378 )
1379 })
1380 .collect();
1381 handles
1382 .into_iter()
1383 .map(|(index, handle)| {
1384 let result = handle
1385 .join()
1386 .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
1387 (index, result)
1388 })
1389 .collect()
1390 });
1391 for (index, result) in collected {
1392 settled[index] = Some((result, Usage::default()));
1393 }
1394 } else {
1395 for &index in &reads {
1396 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1397 }
1398 }
1399 let mut next = 0;
1403 while next < writes.len() {
1404 let index = writes[next];
1405 let run_end = writes[next..]
1406 .iter()
1407 .position(|&index| !specialty[index])
1408 .map_or(writes.len(), |offset| next + offset);
1409 if specialty[index] && run_end - next > 1 {
1410 let group: Vec<usize> = writes[next..run_end].to_vec();
1411 let results = if self.cancel.is_cancelled() {
1412 group
1413 .iter()
1414 .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
1415 .collect()
1416 } else {
1417 let members: Vec<&ToolCall> =
1418 group.iter().map(|&index| &calls[index]).collect();
1419 self.fan_out(&members, sid, spent)
1420 };
1421 for (index, result) in group.into_iter().zip(results) {
1422 settled[index] = Some(result);
1423 }
1424 next = run_end;
1425 } else {
1426 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1427 next += 1;
1428 }
1429 }
1430
1431 settled
1432 .into_iter()
1433 .zip(calls)
1434 .map(|(result, call)| {
1435 result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
1436 })
1437 .collect()
1438 }
1439
1440 fn parallel_eligible(&self, call: &ToolCall) -> bool {
1443 call.invalid_arguments().is_none()
1444 && self
1445 .registry
1446 .get(&call.name)
1447 .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
1448 }
1449
1450 fn resolve_call(&self, call: &ToolCall) -> (Option<ToolResult>, bool) {
1455 if let Some(raw) = call.invalid_arguments() {
1456 return (Some(invalid_arguments_result(call, raw)), false);
1457 }
1458 let Some(tool) = self.registry.get(&call.name) else {
1459 return (Some(self.registry.dispatch(call, &self.context)), false);
1461 };
1462 if !self.context.scope_allows(&call.name) {
1465 return (Some(self.registry.dispatch(call, &self.context)), false);
1466 }
1467 let decision = self.gate.decide(tool.as_ref(), call, &self.context);
1468 if !decision.approved {
1469 return (Some(not_executed(call, decision.reason)), false);
1470 }
1471 (None, !tool.side_effecting() && tool.parallel_safe())
1472 }
1473
1474 async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1475 if self.cancel.is_cancelled() {
1476 (not_executed(call, "cancelled"), Usage::default())
1477 } else {
1478 self.dispatch_call(call, sid).await
1479 }
1480 }
1481
1482 async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1485 let request = match self.delegation(call, &self.context) {
1486 Some(request) => request,
1487 None => return (self.dispatch(call, sid), Usage::default()),
1488 };
1489 let mut span = self.tool_span(call);
1490 let (result, usage) = match request {
1491 Ok(request) => self.delegate(call, request, 1, &self.context).await,
1492 Err(invalid) => (invalid, Usage::default()),
1493 };
1494 span.set(vec![("tool.ok", json!(result.ok))]);
1495 self.tracer.end(span);
1496 self.record_tool_call(call, &result, sid);
1497 (result, usage)
1498 }
1499
1500 fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
1502 let mut span = self.tool_span(call);
1503 let result = self.registry.dispatch(call, &self.context);
1504 span.set(vec![("tool.ok", json!(result.ok))]);
1505 self.tracer.end(span);
1506 self.record_tool_call(call, &result, sid);
1507 result
1508 }
1509
1510 pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
1512 self.tracer.start(
1513 "tool_call",
1514 vec![
1515 ("tool.name", json!(call.name)),
1516 ("gen_ai.tool.name", json!(call.name)),
1517 ],
1518 )
1519 }
1520
1521 pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1522 self.recorder.event(
1523 sid,
1524 "tool_call",
1525 vec![
1526 ("tool", json!(call.name)),
1527 ("ok", json!(result.ok)),
1528 ("arguments", Value::Object(call.arguments.clone())),
1529 ("error", json!(result.error)),
1530 ],
1531 );
1532 self.record_repair(call, result, sid);
1533 }
1534
1535 pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1538 if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
1539 self.recorder.event(
1540 sid,
1541 "tool_args_repaired",
1542 vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
1543 );
1544 }
1545 }
1546
1547 fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
1550 if self.guardrails.egress == EgressMode::Off {
1551 return;
1552 }
1553 for call in calls {
1554 let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
1555 let (report, _) = self.guardrails.inspect_egress(&payload);
1556 if report.flagged() {
1557 self.recorder.event(
1558 sid,
1559 "guardrail",
1560 vec![
1561 ("stage", json!("egress_tool_args")),
1562 ("tool", json!(call.name)),
1563 ("findings", json!(report.summary())),
1564 ],
1565 );
1566 }
1567 }
1568 }
1569
1570 async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1572 match self.resolve_call(call) {
1573 (Some(result), _) => (result, Usage::default()),
1574 (None, _) => self.dispatch_call(call, sid).await,
1575 }
1576 }
1577}
1578
1579pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
1581 ToolResult {
1582 call_id: call.id.clone(),
1583 name: call.name.clone(),
1584 ok: false,
1585 content: String::new(),
1586 error: Some(format!("Not executed: {reason}.")),
1587 metadata: serde_json::Map::new(),
1588 }
1589}
1590
1591fn model_call_attributes(
1593 completion: Option<&crate::types::Completion>,
1594) -> Vec<(&'static str, Value)> {
1595 let Some(completion) = completion else {
1596 return vec![("agent86.completed", json!(false))];
1597 };
1598 let finish = completion
1599 .stop_reason
1600 .as_deref()
1601 .filter(|reason| !reason.is_empty())
1602 .map_or(Value::Null, |reason| json!([reason]));
1603 vec![
1604 ("agent86.completed", json!(true)),
1605 (
1606 "gen_ai.usage.input_tokens",
1607 json!(completion.usage.input_tokens),
1608 ),
1609 (
1610 "gen_ai.usage.output_tokens",
1611 json!(completion.usage.output_tokens),
1612 ),
1613 ("gen_ai.response.finish_reasons", finish),
1614 ("agent86.cost_usd", json!(completion.usage.cost_usd)),
1615 ("agent86.tool_calls", json!(completion.tool_calls.len())),
1616 ]
1617}
1618
1619fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
1622 let mut attributes = vec![("gen_ai.request.model", json!(model))];
1623 if let Some(summary) = &state.last_turn {
1624 attributes.extend([
1625 ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
1626 ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
1627 ("agent86.cost_usd", json!(summary.cost_usd)),
1628 ("agent86.steps", json!(summary.steps)),
1629 ("agent86.tool_calls", json!(summary.tool_calls)),
1630 ("agent86.duration_s", json!(summary.duration_s)),
1631 (
1632 "agent86.phase",
1633 serde_json::to_value(state.phase).unwrap_or(Value::Null),
1634 ),
1635 ]);
1636 }
1637 attributes
1638}
1639
1640fn record_step(state: &mut AgentState, step: Step) {
1642 state.usage = state.usage + step.usage;
1643 state.steps.push(step);
1644}
1645
1646fn message(role: Role, content: &str) -> Message {
1647 Message {
1648 role,
1649 content: content.to_owned(),
1650 tool_calls: Vec::new(),
1651 tool_call_id: None,
1652 name: None,
1653 }
1654}
1655
1656pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
1658 let preview = truncate_chars(raw, 200);
1659 ToolResult {
1660 call_id: call.id.clone(),
1661 name: call.name.clone(),
1662 ok: false,
1663 content: String::new(),
1664 error: Some(format!(
1665 "invalid JSON in tool arguments: {} could not be parsed. \
1666 Call the tool again with its arguments as a single valid JSON object.",
1667 python_repr(&preview)
1668 )),
1669 metadata: serde_json::Map::new(),
1670 }
1671}
1672
1673pub fn observation(result: &ToolResult) -> String {
1676 if result.ok {
1677 return result.content.clone();
1678 }
1679 let error = result.error.as_deref().unwrap_or_default().trim();
1680 let body = result.content.trim();
1681 match (error.is_empty(), body.is_empty()) {
1682 (false, false) => format!("{error}\n{body}"),
1683 (false, true) => error.to_owned(),
1684 (true, false) => body.to_owned(),
1685 (true, true) => "error".to_owned(),
1686 }
1687}
1688
1689pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
1691 let text = python_json_dumps(&Value::Object(arguments.clone()), false);
1692 truncate_chars(&text, 160)
1693}
1694
1695pub fn summarize(result: &ToolResult) -> String {
1697 if !result.ok {
1698 let error = result.error.as_deref().unwrap_or_default().trim();
1699 let content = result.content.trim();
1700 let detail = [error, content, "(failed)"]
1701 .into_iter()
1702 .find(|text| !text.is_empty())
1703 .unwrap_or("(failed)");
1704 return format!("error: {}", first_chars(first_line(detail), 160));
1705 }
1706 let content = result.content.trim();
1707 let head = if content.is_empty() {
1708 "(no output)"
1709 } else {
1710 first_line(content)
1711 };
1712 first_chars(head, 160)
1713}
1714
1715fn first_line(text: &str) -> &str {
1717 let is_break = |c: char| {
1718 matches!(
1719 c,
1720 '\n' | '\r'
1721 | '\u{b}'
1722 | '\u{c}'
1723 | '\u{1c}'
1724 | '\u{1d}'
1725 | '\u{1e}'
1726 | '\u{85}'
1727 | '\u{2028}'
1728 | '\u{2029}'
1729 )
1730 };
1731 text.split(is_break).next().unwrap_or_default()
1732}
1733
1734fn first_chars(text: &str, limit: usize) -> String {
1735 text.chars().take(limit).collect()
1736}
1737
1738fn truncate_chars(text: &str, limit: usize) -> String {
1740 if text.chars().count() <= limit {
1741 text.to_owned()
1742 } else {
1743 format!("{} ...", first_chars(text, limit))
1744 }
1745}
1746
1747#[cfg(test)]
1748mod tests {
1749 use super::*;
1750 use serde_json::json;
1751
1752 fn limits() -> LimitsConfig {
1753 LimitsConfig {
1754 max_steps: 2,
1755 max_cost_usd: 1.0,
1756 max_wall_clock_s: 900,
1757 max_consecutive_errors: 1,
1758 max_context_tokens: 0,
1759 max_output_tokens: 8192,
1760 context_reserve_tokens: 4096,
1761 compaction: CompactionMode::Summarize,
1762 parallel_tools: true,
1763 tool_timeout_s: 60,
1764 }
1765 }
1766
1767 #[test]
1768 fn the_breaker_trips_on_steps_cost_and_error_streaks() {
1769 let mut breaker = CircuitBreaker::new(&limits());
1770 breaker.before_step().unwrap();
1771 breaker.record_step(&Usage::default());
1772 breaker.record_step(&Usage::default());
1773 assert_eq!(
1774 breaker.before_step().unwrap_err().to_string(),
1775 "Circuit tripped: step budget reached (2 steps)"
1776 );
1777
1778 let mut costly = CircuitBreaker::new(&limits());
1779 costly.record_step(&Usage {
1780 cost_usd: 1.25,
1781 ..Usage::default()
1782 });
1783 assert_eq!(
1784 costly.before_step().unwrap_err().to_string(),
1785 "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
1786 );
1787
1788 let mut errors = CircuitBreaker::new(&limits());
1789 errors.record_tool_result(false).unwrap();
1790 errors.record_tool_result(true).unwrap();
1791 errors.record_tool_result(false).unwrap();
1792 assert_eq!(
1793 errors.record_tool_result(false).unwrap_err().to_string(),
1794 "Circuit tripped: aborted after 2 consecutive tool errors"
1795 );
1796 }
1797
1798 fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
1799 ToolResult {
1800 call_id: "c".to_owned(),
1801 name: "t".to_owned(),
1802 ok,
1803 content: content.to_owned(),
1804 error: error.map(str::to_owned),
1805 metadata: serde_json::Map::new(),
1806 }
1807 }
1808
1809 #[test]
1810 fn observations_keep_both_error_and_output() {
1811 assert_eq!(observation(&result(true, "data", None)), "data");
1812 assert_eq!(
1813 observation(&result(false, " out ", Some(" bad "))),
1814 "bad\nout"
1815 );
1816 assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
1817 assert_eq!(observation(&result(false, "", None)), "error");
1818 }
1819
1820 #[test]
1821 fn summaries_show_the_first_line() {
1822 assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
1823 assert_eq!(summarize(&result(true, " ", None)), "(no output)");
1824 assert_eq!(
1825 summarize(&result(false, "", Some("No such file: x\nmore"))),
1826 "error: No such file: x"
1827 );
1828 assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
1829 assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
1830 }
1831
1832 #[test]
1833 fn previews_use_python_json_and_cut_at_160_characters() {
1834 let Value::Object(short) = json!({"path": "src/main.rs"}) else {
1835 unreachable!()
1836 };
1837 assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
1838
1839 let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
1840 unreachable!()
1841 };
1842 let preview = preview_arguments(&long);
1843 assert!(preview.ends_with(" ..."));
1844 assert_eq!(preview.chars().count(), 164);
1845 }
1846
1847 #[test]
1848 fn invalid_json_is_reported_with_a_python_repr_preview() {
1849 let call = ToolCall {
1850 id: "c1".to_owned(),
1851 name: "read_file".to_owned(),
1852 arguments: serde_json::Map::new(),
1853 };
1854 let result = invalid_arguments_result(&call, "{\"path\": ");
1855 assert_eq!(
1856 result.error.as_deref(),
1857 Some(
1858 "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
1859 Call the tool again with its arguments as a single valid JSON object."
1860 )
1861 );
1862 assert!(!result.ok);
1863 assert_eq!(result.call_id, "c1");
1864 }
1865}