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)]
143pub enum TurnEvent<'a> {
144 Text(&'a str),
146 Notice(&'a str),
150 Thinking(&'a str),
153 ToolCall { call: &'a ToolCall, text: &'a str },
155 ToolResult {
158 call: &'a ToolCall,
159 result: &'a ToolResult,
160 observation: &'a str,
161 text: &'a str,
162 },
163 Usage {
167 step: &'a crate::types::Usage,
168 session: &'a crate::types::Usage,
169 },
170 Compacted {
175 notice: &'a str,
176 summary: Option<&'a str>,
177 },
178}
179
180impl<'a> TurnEvent<'a> {
181 pub fn text(&self) -> &'a str {
183 match *self {
184 Self::Text(text)
185 | Self::Notice(text)
186 | Self::ToolCall { text, .. }
187 | Self::ToolResult { text, .. }
188 | Self::Compacted { notice: text, .. } => text,
189 Self::Thinking(_) | Self::Usage { .. } => "",
190 }
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Error)]
196pub enum HarnessError {
197 #[error(transparent)]
198 Provider(#[from] ProviderError),
199
200 #[error("Circuit tripped: {0}")]
201 CircuitTripped(String),
202
203 #[error(
204 "The '{provider}' provider ended its stream for model {} without a final completion. \
205 The response was truncated; retry, or check the endpoint's streaming implementation.",
206 python_repr(model)
207 )]
208 NoFinalCompletion { provider: String, model: String },
209}
210
211impl HarnessError {
212 pub fn python_type(&self) -> &'static str {
215 match self {
216 Self::Provider(_) => "ProviderError",
217 Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
218 }
219 }
220}
221
222pub struct CircuitBreaker {
224 limits: LimitsConfig,
225 steps: u32,
226 cost_usd: f64,
227 consecutive_errors: u32,
228 started: Instant,
229}
230
231impl CircuitBreaker {
232 pub fn new(limits: &LimitsConfig) -> Self {
233 Self {
234 limits: limits.clone(),
235 steps: 0,
236 cost_usd: 0.0,
237 consecutive_errors: 0,
238 started: Instant::now(),
239 }
240 }
241
242 pub fn steps(&self) -> u32 {
243 self.steps
244 }
245
246 pub fn max_steps(&self) -> u32 {
248 self.limits.max_steps
249 }
250
251 pub fn set_max_steps(&mut self, max_steps: u32) {
253 self.limits.max_steps = max_steps;
254 }
255
256 pub fn out_of_steps(&self) -> bool {
258 self.steps >= self.limits.max_steps
259 }
260
261 pub fn before_step(&self) -> Result<(), HarnessError> {
263 let limits = &self.limits;
264 if self.steps >= limits.max_steps {
265 return Err(trip(format!(
266 "step budget reached ({} steps)",
267 limits.max_steps
268 )));
269 }
270 if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
271 return Err(trip(format!(
272 "cost cap reached (${:.4} >= ${})",
273 self.cost_usd,
274 python_float_repr(limits.max_cost_usd)
275 )));
276 }
277 let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
278 if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
279 return Err(trip(format!(
280 "wall-clock limit reached ({}s)",
281 limits.max_wall_clock_s
282 )));
283 }
284 Ok(())
285 }
286
287 pub fn record_step(&mut self, usage: &Usage) {
288 self.steps += 1;
289 self.cost_usd += usage.cost_usd;
290 }
291
292 pub fn cost(&self) -> f64 {
295 self.cost_usd
296 }
297
298 pub fn record_cost(&mut self, cost_usd: f64) {
299 self.cost_usd += cost_usd;
300 }
301
302 pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
303 if ok {
304 self.consecutive_errors = 0;
305 return Ok(());
306 }
307 self.consecutive_errors += 1;
308 if self.consecutive_errors > self.limits.max_consecutive_errors {
309 return Err(trip(format!(
310 "aborted after {} consecutive tool errors",
311 self.consecutive_errors
312 )));
313 }
314 Ok(())
315 }
316}
317
318fn trip(reason: String) -> HarnessError {
319 HarnessError::CircuitTripped(reason)
320}
321
322pub struct Harness {
324 pub provider: Arc<dyn Provider>,
327 pub router: Router,
329 pub tracer: crate::otel::Tracer,
331 pub registry: ToolRegistry,
332 pub context: ToolContext,
333 pub limits: LimitsConfig,
334 pub agents: AgentsConfig,
336 pub system: Message,
337 pub max_tokens: u32,
340 pub session_limits: crate::limits::SessionLimits,
343 pub context_window: u64,
346 pub gate: ApprovalGate,
348 pub guardrails: Guardrails,
350 pub recorder: Recorder,
352 pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
355 pub memory: Option<crate::session::SessionStore>,
358 pub cancel: CancelToken,
360 pub subagents: crate::subagent::SubagentState,
363}
364
365impl Harness {
366 pub(crate) fn system_message(&self, extra: Option<&str>) -> Message {
371 let offered = self.delegation_offered(&self.context, 0);
372 if let Some((persona, preloaded)) = self.subagents.main() {
374 return self.filtered_system(&persona, &self.context, &preloaded, offered, extra);
375 }
376 self.system_for(&self.context, offered, extra)
377 }
378
379 pub(crate) fn system_for(
383 &self,
384 ctx: &ToolContext,
385 delegation_offered: bool,
386 extra: Option<&str>,
387 ) -> Message {
388 let mut system = self.system.clone();
389 if let Some(section) = self
390 .mcp
391 .as_ref()
392 .map(|mcp| mcp.prompt_section())
393 .filter(|section| !section.is_empty())
394 {
395 system.content = format!("{}\n\n{section}", system.content);
396 }
397 if delegation_offered {
398 if let Some(section) = self.specialty_listing(ctx) {
399 system.content = format!("{}\n\n{section}", system.content);
400 }
401 }
402 if let Some(section) = ctx.secrets.prompt_section() {
403 system.content = format!("{}\n\n{section}", system.content);
404 }
405 if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
406 system.content = format!("{}\n\n{extra}", system.content);
407 }
408 system
409 }
410
411 pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
416 self.context_budget_with(
417 system,
418 specs,
419 self.active_context_window(),
420 self.output_cap(),
421 )
422 }
423
424 pub(crate) fn context_budget_with(
427 &self,
428 system: &Message,
429 specs: &[ToolSpec],
430 window: u64,
431 output_cap: u32,
432 ) -> u64 {
433 let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
434 conversation_budget(
435 window,
436 overhead,
437 self.limits.context_reserve_tokens,
438 u64::from(output_cap),
439 self.limits.max_context_tokens,
440 )
441 }
442
443 async fn compact_if_needed(
453 &self,
454 state: &mut AgentState,
455 extra_system: Option<&str>,
456 summary: &mut TurnSummary,
457 breaker: &mut CircuitBreaker,
458 protect_from: usize,
459 ) -> Option<(String, usize, Option<String>)> {
460 if self.limits.compaction != CompactionMode::Summarize {
461 return None;
462 }
463 let system = self.system_message(extra_system);
464 let budget = self.context_budget(&system, &self.registry.specs());
465 if fits(&state.messages, budget) {
466 return None;
467 }
468 let cut = compaction_cut(&state.messages, budget, KEEP_RECENT, Some(protect_from));
469 if cut == 0 {
470 return None;
473 }
474 let sid = state.session_id.clone();
475 let prefix = &state.messages[..cut];
476 let dropped_tokens = count_tokens(prefix);
477 let summarizer = self.summary_provider();
478 let request = CompletionRequest {
479 model: summarizer.model().to_owned(),
480 messages: vec![
481 message(Role::System, SUMMARY_SYSTEM_PROMPT),
482 message(Role::User, &render_transcript(prefix)),
483 ],
484 tools: Vec::new(),
485 temperature: 0.0,
486 max_tokens: Some(SUMMARY_MAX_TOKENS * 2),
488 stream: false,
489 };
490 let completion = tokio::select! {
491 biased;
492 () = self.cancel.cancelled() => return None,
494 completion = summarizer.complete(request) => completion,
495 };
496 let failed = |status: &str, error: Option<String>| {
497 let mut fields = vec![
498 ("status", json!(status)),
499 ("fallback", json!("drop")),
500 ("dropped", json!(cut)),
501 ];
502 if let Some(error) = error {
503 fields.push(("error", json!(error)));
504 }
505 self.recorder.event(&sid, "compaction", fields);
506 Some((compaction_failed_notice(cut), 0, None))
507 };
508 let completion = match completion {
509 Ok(completion) => completion,
510 Err(error) => return failed("failed", Some(format!("ProviderError: {error}"))),
511 };
512 let text = python_strip(&completion.text).to_owned();
513 if text.is_empty() {
514 return failed("empty", None);
515 }
516
517 if let Some(memory) = &self.memory {
519 let _ = memory.record_compaction(&sid, &text, prefix);
520 }
521 let before = state.messages.len();
522 let kept = state.messages.split_off(cut);
523 state.messages = apply_summary(&text, kept);
524 summary.compactions += 1;
525 summary.add_usage(&completion.usage);
526 breaker.record_cost(completion.usage.cost_usd);
527 self.recorder.event(
528 &sid,
529 "compaction",
530 vec![
531 ("status", json!("ok")),
532 ("dropped", json!(cut)),
533 ("dropped_tokens", json!(dropped_tokens)),
534 (
535 "summary_tokens",
536 json!(count_tokens(&[message(Role::User, &text)])),
537 ),
538 ("kept", json!(state.messages.len())),
539 ("model", json!(summarizer.model())),
540 ],
541 );
542 if let Some(memory) = &self.memory {
545 let _ = memory.persist(state);
546 }
547 Some((
548 compacted_notice(cut),
549 before - state.messages.len(),
550 Some(text),
551 ))
552 }
553
554 pub async fn run_turn(
561 &self,
562 state: &mut AgentState,
563 goal: &str,
564 on_text: impl FnMut(&str),
565 ) -> Result<String, HarnessError> {
566 self.run_turn_as(state, goal, goal, on_text).await
567 }
568
569 pub async fn run_turn_as(
573 &self,
574 state: &mut AgentState,
575 user_text: &str,
576 display_text: &str,
577 mut on_text: impl FnMut(&str),
578 ) -> Result<String, HarnessError> {
579 self.run_turn_events(state, user_text, display_text, |event| {
580 on_text(event.text())
581 })
582 .await
583 }
584
585 pub async fn run_turn_events(
589 &self,
590 state: &mut AgentState,
591 user_text: &str,
592 display_text: &str,
593 on_event: impl FnMut(TurnEvent<'_>),
594 ) -> Result<String, HarnessError> {
595 self.run_turn_with(state, user_text, display_text, None, on_event)
596 .await
597 }
598
599 pub async fn run_skill_turn(
606 &self,
607 state: &mut AgentState,
608 skill: &Arc<crate::skills::Skill>,
609 task: &str,
610 display_text: &str,
611 on_event: impl FnMut(TurnEvent<'_>),
612 ) -> Result<String, HarnessError> {
613 let user_text = crate::skills::skill_request(skill, task);
614 self.run_turn_with(state, &user_text, display_text, Some(skill), on_event)
615 .await
616 }
617
618 async fn run_turn_with(
619 &self,
620 state: &mut AgentState,
621 user_text: &str,
622 display_text: &str,
623 skill: Option<&Arc<crate::skills::Skill>>,
624 on_event: impl FnMut(TurnEvent<'_>),
625 ) -> Result<String, HarnessError> {
626 self.cancel.clear();
628 self.context.clear_skill();
633 if let Some(skill) = skill {
634 self.context.activate_skill(skill);
635 }
636 let started = Instant::now();
637 let mut span = self.tracer.start(
639 "turn",
640 vec![
641 ("session.id", json!(state.session_id)),
642 (
643 "gen_ai.request.model",
644 json!(self.active_provider().model()),
645 ),
646 ],
647 );
648 let mut summary = TurnSummary::default();
649 let secrets = &self.context.secrets;
652 let (user_text, display_text) = (secrets.redact(user_text), secrets.redact(display_text));
653 let result = self
654 .turn(state, &user_text, &display_text, &mut summary, on_event)
655 .await;
656 self.context.clear_skill();
657 summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
658 state.last_turn = Some(summary);
659 if let Err(error) = &result {
660 state.phase = AgentPhase::Error;
661 let reason = match error {
662 HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
663 HarnessError::Provider(detail) => {
664 format!("provider stream failed: ProviderError: {detail}")
665 }
666 HarnessError::NoFinalCompletion { .. } => {
667 "provider stream ended without a final completion".to_owned()
668 }
669 };
670 self.recorder.event(
671 &state.session_id,
672 "turn_end",
673 vec![("status", json!("error")), ("reason", json!(reason))],
674 );
675 }
676 span.set(turn_attributes(state, self.active_provider().model()));
679 if let Err(error) = &result {
680 span.fail(error.python_type(), &error.to_string());
681 }
682 self.tracer.end(span);
683 result
684 }
685
686 async fn turn(
687 &self,
688 state: &mut AgentState,
689 goal: &str,
690 display_text: &str,
691 summary: &mut TurnSummary,
692 mut on_event: impl FnMut(TurnEvent<'_>),
693 ) -> Result<String, HarnessError> {
694 let mut output = String::new();
695 let mut emit = |event: TurnEvent<'_>| {
696 output.push_str(event.text());
697 on_event(event);
698 };
699
700 let sid = state.session_id.clone();
701 self.recorder
702 .event(&sid, "turn_start", vec![("task", json!(display_text))]);
703
704 let report = self.guardrails.inspect_ingress(goal);
706 if report.flagged() {
707 self.recorder.event(
708 &sid,
709 "guardrail",
710 vec![
711 ("stage", json!("ingress_input")),
712 ("findings", json!(report.summary())),
713 ],
714 );
715 if self.guardrails.should_block(&report) {
716 let refusal = format!(
717 "Refused: input tripped the ingress guardrail ({}).",
718 report.summary()
719 );
720 state.messages.push(message(Role::User, goal));
721 state.messages.push(message(Role::Assistant, &refusal));
722 state.phase = AgentPhase::Error;
723 self.recorder
724 .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
725 emit(TurnEvent::Text(&refusal));
726 return Ok(output);
727 }
728 emit(TurnEvent::Notice(&format!(
729 "[guardrail] input flagged: {}\n",
730 report.summary()
731 )));
732 }
733
734 let buffering = self.guardrails.egress == EgressMode::Redact;
737
738 self.route(goal, &sid)?;
740 let provider = self.active_provider();
741
742 let recall_note = self
744 .memory
745 .as_ref()
746 .and_then(|memory| memory.recall_note(goal));
747 let time = time_note(&jiff::ZonedDateTime::now());
749 let recall_note = Some(match recall_note {
750 Some(recalled) => format!("{time}\n\n{recalled}"),
751 None => time,
752 });
753 let mut turn_start = state.messages.len();
756 state.messages.push(message(Role::User, goal));
757 let mut limits = self.limits.clone();
758 limits.max_steps = self.max_steps();
759 let mut breaker = CircuitBreaker::new(&limits);
760 let mut continuation_start: Option<usize> = None;
762 let mut continuation_parts: Vec<String> = Vec::new();
763 let mut nudged = false;
767 let mut ask_again = false;
768 let mut unanswered_thinking = String::new();
769
770 loop {
771 if self.cancel.is_cancelled() {
774 self.cancelled(state, breaker.steps(), &mut emit);
775 return Ok(output);
776 }
777 if breaker.out_of_steps() {
779 match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
780 Some(raised) => breaker.set_max_steps(raised),
781 None if self.cancel.is_cancelled() => {
783 self.cancelled(state, breaker.steps(), &mut emit);
784 return Ok(output);
785 }
786 None => {}
787 }
788 }
789 breaker.before_step()?;
790
791 if let Some((notice, removed, compacted)) = self
794 .compact_if_needed(
795 state,
796 recall_note.as_deref(),
797 summary,
798 &mut breaker,
799 turn_start,
800 )
801 .await
802 {
803 turn_start -= removed;
806 if let Some(start) = continuation_start.as_mut() {
807 *start -= removed;
808 }
809 emit(TurnEvent::Compacted {
812 notice: ¬ice,
813 summary: compacted.as_deref(),
814 });
815 }
816
817 let mut completion = {
818 let system = self.system_message(recall_note.as_deref());
819 let mut tools = self.registry.specs();
820 tools.retain(|spec| self.context.scope_allows(&spec.name));
822 let budget = self.context_budget(&system, &tools);
823 let conversation = fit(&state.messages, budget);
824 let mut request_messages = Vec::with_capacity(conversation.len() + 1);
825 request_messages.push(system);
826 request_messages.extend(conversation.iter().cloned());
827 if std::mem::take(&mut ask_again) {
828 request_messages.push(message(Role::User, ANSWER_PROMPT));
829 }
830 let request = CompletionRequest {
831 model: provider.model().to_owned(),
832 messages: request_messages,
833 tools,
834 temperature: 0.0,
835 max_tokens: Some(self.output_cap()),
836 stream: true,
837 };
838 let mut span = self.tracer.start(
840 "model_call",
841 vec![
842 ("gen_ai.system", json!(provider.name())),
843 ("gen_ai.request.model", json!(provider.model())),
844 ("agent86.step", json!(breaker.steps() + 1)),
845 ],
846 );
847 let mut stream = provider.stream(request);
848 let mut completion = None;
849 let mut buffered = String::new();
850 let mut redactor = StreamRedactor::default();
853 let mut thinking_redactor = StreamRedactor::default();
854 loop {
855 let next = tokio::select! {
858 biased;
859 () = self.cancel.cancelled() => None,
860 delta = stream.next() => Some(delta),
861 };
862 let Some(Some(delta)) = next else { break };
863 let delta = match delta {
864 Ok(delta) => delta,
865 Err(error) => {
866 span.set(model_call_attributes(None));
867 span.fail("ProviderError", &error.to_string());
868 self.tracer.end(span);
869 return Err(error.into());
870 }
871 };
872 if !delta.thinking.is_empty() && !buffering {
875 let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
876 if !shown.is_empty() {
877 emit(TurnEvent::Thinking(&shown));
878 }
879 }
880 if !delta.text.is_empty() {
881 if buffering {
882 buffered.push_str(&delta.text);
883 } else {
884 let shown = redactor.push(&self.context.secrets, &delta.text);
885 if !shown.is_empty() {
886 emit(TurnEvent::Text(&shown));
887 }
888 }
889 }
890 if delta.done && delta.completion.is_some() {
891 completion = delta.completion;
892 }
893 }
894 drop(stream);
895 let held = thinking_redactor.finish(&self.context.secrets);
896 if !held.is_empty() {
897 emit(TurnEvent::Thinking(&held));
898 }
899 let held = redactor.finish(&self.context.secrets);
900 if !held.is_empty() {
901 emit(TurnEvent::Text(&held));
902 }
903 span.set(model_call_attributes(completion.as_ref()));
904 self.tracer.end(span);
905 if self.cancel.is_cancelled() {
906 let partial = self
908 .guardrails
909 .inspect_egress(&self.context.secrets.redact(&buffered))
910 .1;
911 if !partial.is_empty() {
912 emit(TurnEvent::Text(&partial));
913 }
914 self.cancelled(state, breaker.steps(), &mut emit);
915 return Ok(output);
916 }
917 completion.ok_or_else(|| HarnessError::NoFinalCompletion {
918 provider: provider.name().to_owned(),
919 model: provider.model().to_owned(),
920 })?
921 };
922
923 breaker.record_step(&completion.usage);
924 summary.steps = u64::from(breaker.steps());
925 summary.add_usage(&completion.usage);
926 emit(TurnEvent::Usage {
929 step: &completion.usage,
930 session: &(state.usage + completion.usage),
931 });
932 let names: Vec<&str> = completion
933 .tool_calls
934 .iter()
935 .map(|call| call.name.as_str())
936 .collect();
937 self.recorder.event(
938 &sid,
939 "model_call",
940 vec![
941 ("step", json!(breaker.steps())),
942 ("model", json!(provider.model())),
943 ("input_tokens", json!(completion.usage.input_tokens)),
944 ("output_tokens", json!(completion.usage.output_tokens)),
945 ("cost_usd", json!(completion.usage.cost_usd)),
946 ("stop_reason", json!(completion.stop_reason)),
947 ("tool_calls", json!(names)),
948 ],
949 );
950
951 if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
952 emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
953 }
954 let stopped = completion
957 .stop_reason
958 .as_deref()
959 .and_then(|reason| reason.strip_prefix(crate::provider::google::STOPPED_PREFIX))
960 .map(str::to_owned);
961 if let Some(reason) = &stopped {
962 emit(TurnEvent::Notice(&format!(
963 "\n[{} stopped the reply: {reason}]\n",
964 provider.name()
965 )));
966 }
967
968 let mut from_thinking = false;
974 if completion.tool_calls.is_empty()
975 && completion.stop_reason.as_deref() != Some("max_tokens")
976 && stopped.is_none()
977 && completion.text.trim().is_empty()
978 && continuation_start.is_none()
979 {
980 if !completion.thinking.trim().is_empty() {
981 unanswered_thinking = std::mem::take(&mut completion.thinking);
982 }
983 if !nudged && !breaker.out_of_steps() {
984 nudged = true;
985 ask_again = true;
986 self.recorder.event(
987 &sid,
988 "empty_answer",
989 vec![
990 ("step", json!(breaker.steps())),
991 ("model", json!(provider.model())),
992 ("thinking_chars", json!(unanswered_thinking.chars().count())),
993 ],
994 );
995 record_step(
996 state,
997 Step {
998 index: state.steps.len() as u64 + 1,
999 phase: AgentPhase::Execute,
1000 thought: String::new(),
1001 tool_calls: Vec::new(),
1002 results: Vec::new(),
1003 usage: completion.usage,
1004 },
1005 );
1006 self.checkpoint(state);
1007 emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1008 continue;
1009 }
1010 if unanswered_thinking.trim().is_empty() {
1011 emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1012 if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1015 emit(TurnEvent::Notice(&format!(
1016 "{}\n",
1017 crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1018 )));
1019 }
1020 } else {
1021 completion.text = std::mem::take(&mut unanswered_thinking);
1022 from_thinking = true;
1023 emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1024 }
1025 }
1026
1027 let answer = self.context.secrets.redact(&completion.text);
1030 let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1031 let text = if buffering {
1032 if !redacted.is_empty() {
1033 emit(TurnEvent::Text(&redacted));
1034 }
1035 redacted
1036 } else {
1037 if from_thinking {
1039 emit(TurnEvent::Text(&answer));
1040 }
1041 answer
1042 };
1043 if egress.flagged() {
1044 self.recorder.event(
1045 &sid,
1046 "guardrail",
1047 vec![
1048 ("stage", json!("egress")),
1049 ("findings", json!(egress.summary())),
1050 ],
1051 );
1052 emit(TurnEvent::Notice(&format!(
1053 "\n[guardrail] output flagged: {}\n",
1054 egress.summary()
1055 )));
1056 }
1057 let tool_calls = completion.tool_calls;
1058 self.scan_tool_arguments(&tool_calls, &sid);
1059 let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1060 if cut_off
1065 && tool_calls.is_empty()
1066 && text.trim().is_empty()
1067 && continuation_start.is_none()
1068 {
1069 let cap = self.output_cap();
1070 if self
1071 .raise_limit(LimitKind::Output, None, &sid, cap, false)
1072 .is_some()
1073 {
1074 record_step(
1075 state,
1076 Step {
1077 index: state.steps.len() as u64 + 1,
1078 phase: AgentPhase::Execute,
1079 thought: String::new(),
1080 tool_calls: Vec::new(),
1081 results: Vec::new(),
1082 usage: completion.usage,
1083 },
1084 );
1085 self.checkpoint(state);
1086 continue;
1087 }
1088 }
1089 let mut step = Step {
1090 index: state.steps.len() as u64 + 1,
1091 phase: AgentPhase::Execute,
1092 thought: text.clone(),
1093 tool_calls: tool_calls.clone(),
1094 results: Vec::new(),
1095 usage: completion.usage,
1096 };
1097 state.messages.push(Message {
1098 tool_calls: tool_calls.clone(),
1099 ..message(Role::Assistant, &text)
1100 });
1101
1102 if tool_calls.is_empty() {
1103 if cut_off && summary.continuations < MAX_CONTINUATIONS {
1104 summary.continuations += 1;
1105 continuation_start.get_or_insert(state.messages.len() - 1);
1106 continuation_parts.push(text);
1107 state.messages.push(message(Role::User, CONTINUE_PROMPT));
1108 record_step(state, step);
1109 self.checkpoint(state);
1110 self.recorder.event(
1111 &sid,
1112 "continuation",
1113 vec![
1114 ("index", json!(summary.continuations)),
1115 ("step", json!(breaker.steps())),
1116 ("model", json!(provider.model())),
1117 (
1118 "chars",
1119 json!(continuation_parts
1120 .last()
1121 .map_or(0, |part| part.chars().count())),
1122 ),
1123 ],
1124 );
1125 emit(TurnEvent::Notice(&continuation_notice(
1126 summary.continuations,
1127 )));
1128 continue;
1129 }
1130 if let Some(start) = continuation_start {
1131 continuation_parts.push(text);
1133 let joined = continuation_parts.concat();
1134 state.messages.truncate(start);
1135 state.messages.push(message(Role::Assistant, &joined));
1136 step.thought = joined;
1137 }
1138 let outcome = step.thought.clone();
1139 record_step(state, step);
1140 state.phase = AgentPhase::Done;
1141 self.recorder.event(
1142 &sid,
1143 "turn_end",
1144 vec![
1145 ("status", json!("done")),
1146 ("steps", json!(breaker.steps())),
1147 ("continuations", json!(summary.continuations)),
1148 ],
1149 );
1150 if let Some(memory) = &self.memory {
1151 let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1153 }
1154 return Ok(output);
1155 }
1156
1157 continuation_start = None;
1159 continuation_parts.clear();
1160
1161 if self.cancel.is_cancelled() {
1165 for call in &tool_calls {
1166 let result = not_executed(call, "cancelled");
1167 state.messages.push(Message {
1168 tool_call_id: Some(call.id.clone()),
1169 name: Some(call.name.clone()),
1170 ..message(Role::Tool, &observation(&result))
1171 });
1172 step.results.push(result);
1173 }
1174 record_step(state, step);
1175 self.cancelled(state, breaker.steps(), &mut emit);
1176 return Ok(output);
1177 }
1178
1179 for call in &tool_calls {
1181 let text = format!(
1182 "\n[tool] {}({})\n",
1183 call.name,
1184 preview_arguments(&call.arguments)
1185 );
1186 emit(TurnEvent::ToolCall { call, text: &text });
1187 }
1188 let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1189 for notice in self.take_notices() {
1193 emit(TurnEvent::Notice(&format!("{notice}\n")));
1194 }
1195 for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1196 summary.tool_calls += 1;
1197 summary.add_usage(&delegated);
1200 step.usage = step.usage + delegated;
1201 breaker.record_cost(delegated.cost_usd);
1202 let (content, findings) = self.guardrails.observe(observation(&result));
1203 if let Some(findings) = findings {
1204 self.recorder.event(
1205 &sid,
1206 "guardrail",
1207 vec![
1208 ("stage", json!("observation")),
1209 ("tool", json!(call.name)),
1210 ("findings", json!(findings)),
1211 ],
1212 );
1213 }
1214 emit(TurnEvent::ToolResult {
1215 call,
1216 result: &result,
1217 observation: &content,
1218 text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1219 });
1220 state.messages.push(Message {
1221 tool_call_id: Some(call.id.clone()),
1222 name: Some(call.name.clone()),
1223 ..message(Role::Tool, &content)
1224 });
1225 let ok = result.ok;
1226 step.results.push(result);
1227 if let Err(tripped) = breaker.record_tool_result(ok) {
1228 record_step(state, step);
1229 return Err(tripped);
1230 }
1231 }
1232 record_step(state, step);
1235 self.checkpoint(state);
1236 if self.cancel.is_cancelled() {
1237 self.cancelled(state, breaker.steps(), &mut emit);
1238 return Ok(output);
1239 }
1240 }
1241 }
1242
1243 fn checkpoint(&self, state: &mut AgentState) {
1250 state.phase = AgentPhase::Execute;
1251 if let Some(memory) = &self.memory {
1252 let _ = memory.persist(state);
1253 }
1254 }
1255
1256 fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
1260 state.phase = AgentPhase::Error;
1261 self.recorder.event(
1262 &state.session_id,
1263 "turn_end",
1264 vec![
1265 ("status", json!("cancelled")),
1266 ("reason", json!("cancelled")),
1267 ("steps", json!(steps)),
1268 ],
1269 );
1270 emit(TurnEvent::Notice(CANCELLED_NOTICE));
1271 }
1272
1273 async fn execute_batch(
1287 &self,
1288 calls: &[ToolCall],
1289 sid: &str,
1290 spent: f64,
1291 ) -> Vec<(ToolResult, Usage)> {
1292 let eligible = calls
1293 .iter()
1294 .filter(|call| self.parallel_eligible(call))
1295 .count();
1296 let specialty: Vec<bool> = calls
1297 .iter()
1298 .map(|call| self.is_specialty_delegation(call))
1299 .collect();
1300 let any_specialty = specialty.contains(&true);
1301 if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
1302 let mut results = Vec::with_capacity(calls.len());
1304 for call in calls {
1305 results.push(if self.cancel.is_cancelled() {
1306 (not_executed(call, "cancelled"), Usage::default())
1307 } else {
1308 self.execute_tool(call, sid).await
1309 });
1310 }
1311 return results;
1312 }
1313
1314 let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
1315 let mut may_parallel = Vec::with_capacity(calls.len());
1316 for call in calls {
1317 let (result, parallel) = self.resolve_call(call);
1318 settled.push(result.map(|result| (result, Usage::default())));
1319 may_parallel.push(parallel);
1320 }
1321 let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
1322 let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
1323 let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
1324
1325 if reads.len() > 1 {
1326 let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
1327 let handles: Vec<_> = reads
1328 .iter()
1329 .map(|&index| {
1330 (
1331 index,
1332 scope.spawn(move || self.dispatch(&calls[index], sid)),
1333 )
1334 })
1335 .collect();
1336 handles
1337 .into_iter()
1338 .map(|(index, handle)| {
1339 let result = handle
1340 .join()
1341 .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
1342 (index, result)
1343 })
1344 .collect()
1345 });
1346 for (index, result) in collected {
1347 settled[index] = Some((result, Usage::default()));
1348 }
1349 } else {
1350 for &index in &reads {
1351 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1352 }
1353 }
1354 let mut next = 0;
1358 while next < writes.len() {
1359 let index = writes[next];
1360 let run_end = writes[next..]
1361 .iter()
1362 .position(|&index| !specialty[index])
1363 .map_or(writes.len(), |offset| next + offset);
1364 if specialty[index] && run_end - next > 1 {
1365 let group: Vec<usize> = writes[next..run_end].to_vec();
1366 let results = if self.cancel.is_cancelled() {
1367 group
1368 .iter()
1369 .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
1370 .collect()
1371 } else {
1372 let members: Vec<&ToolCall> =
1373 group.iter().map(|&index| &calls[index]).collect();
1374 self.fan_out(&members, sid, spent)
1375 };
1376 for (index, result) in group.into_iter().zip(results) {
1377 settled[index] = Some(result);
1378 }
1379 next = run_end;
1380 } else {
1381 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1382 next += 1;
1383 }
1384 }
1385
1386 settled
1387 .into_iter()
1388 .zip(calls)
1389 .map(|(result, call)| {
1390 result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
1391 })
1392 .collect()
1393 }
1394
1395 fn parallel_eligible(&self, call: &ToolCall) -> bool {
1398 call.invalid_arguments().is_none()
1399 && self
1400 .registry
1401 .get(&call.name)
1402 .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
1403 }
1404
1405 fn resolve_call(&self, call: &ToolCall) -> (Option<ToolResult>, bool) {
1410 if let Some(raw) = call.invalid_arguments() {
1411 return (Some(invalid_arguments_result(call, raw)), false);
1412 }
1413 let Some(tool) = self.registry.get(&call.name) else {
1414 return (Some(self.registry.dispatch(call, &self.context)), false);
1416 };
1417 if !self.context.scope_allows(&call.name) {
1420 return (Some(self.registry.dispatch(call, &self.context)), false);
1421 }
1422 let decision = self.gate.decide(tool.as_ref(), call, &self.context);
1423 if !decision.approved {
1424 return (Some(not_executed(call, decision.reason)), false);
1425 }
1426 (None, !tool.side_effecting() && tool.parallel_safe())
1427 }
1428
1429 async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1430 if self.cancel.is_cancelled() {
1431 (not_executed(call, "cancelled"), Usage::default())
1432 } else {
1433 self.dispatch_call(call, sid).await
1434 }
1435 }
1436
1437 async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1440 let request = match self.delegation(call, &self.context) {
1441 Some(request) => request,
1442 None => return (self.dispatch(call, sid), Usage::default()),
1443 };
1444 let mut span = self.tool_span(call);
1445 let (result, usage) = match request {
1446 Ok(request) => self.delegate(call, request, 1, &self.context).await,
1447 Err(invalid) => (invalid, Usage::default()),
1448 };
1449 span.set(vec![("tool.ok", json!(result.ok))]);
1450 self.tracer.end(span);
1451 self.record_tool_call(call, &result, sid);
1452 (result, usage)
1453 }
1454
1455 fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
1457 let mut span = self.tool_span(call);
1458 let result = self.registry.dispatch(call, &self.context);
1459 span.set(vec![("tool.ok", json!(result.ok))]);
1460 self.tracer.end(span);
1461 self.record_tool_call(call, &result, sid);
1462 result
1463 }
1464
1465 pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
1467 self.tracer.start(
1468 "tool_call",
1469 vec![
1470 ("tool.name", json!(call.name)),
1471 ("gen_ai.tool.name", json!(call.name)),
1472 ],
1473 )
1474 }
1475
1476 pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1477 self.recorder.event(
1478 sid,
1479 "tool_call",
1480 vec![
1481 ("tool", json!(call.name)),
1482 ("ok", json!(result.ok)),
1483 ("arguments", Value::Object(call.arguments.clone())),
1484 ("error", json!(result.error)),
1485 ],
1486 );
1487 self.record_repair(call, result, sid);
1488 }
1489
1490 pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1493 if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
1494 self.recorder.event(
1495 sid,
1496 "tool_args_repaired",
1497 vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
1498 );
1499 }
1500 }
1501
1502 fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
1505 if self.guardrails.egress == EgressMode::Off {
1506 return;
1507 }
1508 for call in calls {
1509 let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
1510 let (report, _) = self.guardrails.inspect_egress(&payload);
1511 if report.flagged() {
1512 self.recorder.event(
1513 sid,
1514 "guardrail",
1515 vec![
1516 ("stage", json!("egress_tool_args")),
1517 ("tool", json!(call.name)),
1518 ("findings", json!(report.summary())),
1519 ],
1520 );
1521 }
1522 }
1523 }
1524
1525 async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1527 match self.resolve_call(call) {
1528 (Some(result), _) => (result, Usage::default()),
1529 (None, _) => self.dispatch_call(call, sid).await,
1530 }
1531 }
1532}
1533
1534pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
1536 ToolResult {
1537 call_id: call.id.clone(),
1538 name: call.name.clone(),
1539 ok: false,
1540 content: String::new(),
1541 error: Some(format!("Not executed: {reason}.")),
1542 metadata: serde_json::Map::new(),
1543 }
1544}
1545
1546fn model_call_attributes(
1548 completion: Option<&crate::types::Completion>,
1549) -> Vec<(&'static str, Value)> {
1550 let Some(completion) = completion else {
1551 return vec![("agent86.completed", json!(false))];
1552 };
1553 let finish = completion
1554 .stop_reason
1555 .as_deref()
1556 .filter(|reason| !reason.is_empty())
1557 .map_or(Value::Null, |reason| json!([reason]));
1558 vec![
1559 ("agent86.completed", json!(true)),
1560 (
1561 "gen_ai.usage.input_tokens",
1562 json!(completion.usage.input_tokens),
1563 ),
1564 (
1565 "gen_ai.usage.output_tokens",
1566 json!(completion.usage.output_tokens),
1567 ),
1568 ("gen_ai.response.finish_reasons", finish),
1569 ("agent86.cost_usd", json!(completion.usage.cost_usd)),
1570 ("agent86.tool_calls", json!(completion.tool_calls.len())),
1571 ]
1572}
1573
1574fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
1577 let mut attributes = vec![("gen_ai.request.model", json!(model))];
1578 if let Some(summary) = &state.last_turn {
1579 attributes.extend([
1580 ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
1581 ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
1582 ("agent86.cost_usd", json!(summary.cost_usd)),
1583 ("agent86.steps", json!(summary.steps)),
1584 ("agent86.tool_calls", json!(summary.tool_calls)),
1585 ("agent86.duration_s", json!(summary.duration_s)),
1586 (
1587 "agent86.phase",
1588 serde_json::to_value(state.phase).unwrap_or(Value::Null),
1589 ),
1590 ]);
1591 }
1592 attributes
1593}
1594
1595fn record_step(state: &mut AgentState, step: Step) {
1597 state.usage = state.usage + step.usage;
1598 state.steps.push(step);
1599}
1600
1601fn message(role: Role, content: &str) -> Message {
1602 Message {
1603 role,
1604 content: content.to_owned(),
1605 tool_calls: Vec::new(),
1606 tool_call_id: None,
1607 name: None,
1608 }
1609}
1610
1611pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
1613 let preview = truncate_chars(raw, 200);
1614 ToolResult {
1615 call_id: call.id.clone(),
1616 name: call.name.clone(),
1617 ok: false,
1618 content: String::new(),
1619 error: Some(format!(
1620 "invalid JSON in tool arguments: {} could not be parsed. \
1621 Call the tool again with its arguments as a single valid JSON object.",
1622 python_repr(&preview)
1623 )),
1624 metadata: serde_json::Map::new(),
1625 }
1626}
1627
1628pub fn observation(result: &ToolResult) -> String {
1631 if result.ok {
1632 return result.content.clone();
1633 }
1634 let error = result.error.as_deref().unwrap_or_default().trim();
1635 let body = result.content.trim();
1636 match (error.is_empty(), body.is_empty()) {
1637 (false, false) => format!("{error}\n{body}"),
1638 (false, true) => error.to_owned(),
1639 (true, false) => body.to_owned(),
1640 (true, true) => "error".to_owned(),
1641 }
1642}
1643
1644pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
1646 let text = python_json_dumps(&Value::Object(arguments.clone()), false);
1647 truncate_chars(&text, 160)
1648}
1649
1650pub fn summarize(result: &ToolResult) -> String {
1652 if !result.ok {
1653 let error = result.error.as_deref().unwrap_or_default().trim();
1654 let content = result.content.trim();
1655 let detail = [error, content, "(failed)"]
1656 .into_iter()
1657 .find(|text| !text.is_empty())
1658 .unwrap_or("(failed)");
1659 return format!("error: {}", first_chars(first_line(detail), 160));
1660 }
1661 let content = result.content.trim();
1662 let head = if content.is_empty() {
1663 "(no output)"
1664 } else {
1665 first_line(content)
1666 };
1667 first_chars(head, 160)
1668}
1669
1670fn first_line(text: &str) -> &str {
1672 let is_break = |c: char| {
1673 matches!(
1674 c,
1675 '\n' | '\r'
1676 | '\u{b}'
1677 | '\u{c}'
1678 | '\u{1c}'
1679 | '\u{1d}'
1680 | '\u{1e}'
1681 | '\u{85}'
1682 | '\u{2028}'
1683 | '\u{2029}'
1684 )
1685 };
1686 text.split(is_break).next().unwrap_or_default()
1687}
1688
1689fn first_chars(text: &str, limit: usize) -> String {
1690 text.chars().take(limit).collect()
1691}
1692
1693fn truncate_chars(text: &str, limit: usize) -> String {
1695 if text.chars().count() <= limit {
1696 text.to_owned()
1697 } else {
1698 format!("{} ...", first_chars(text, limit))
1699 }
1700}
1701
1702#[cfg(test)]
1703mod tests {
1704 use super::*;
1705 use serde_json::json;
1706
1707 fn limits() -> LimitsConfig {
1708 LimitsConfig {
1709 max_steps: 2,
1710 max_cost_usd: 1.0,
1711 max_wall_clock_s: 900,
1712 max_consecutive_errors: 1,
1713 max_context_tokens: 0,
1714 max_output_tokens: 8192,
1715 context_reserve_tokens: 4096,
1716 compaction: CompactionMode::Summarize,
1717 parallel_tools: true,
1718 tool_timeout_s: 60,
1719 }
1720 }
1721
1722 #[test]
1723 fn the_breaker_trips_on_steps_cost_and_error_streaks() {
1724 let mut breaker = CircuitBreaker::new(&limits());
1725 breaker.before_step().unwrap();
1726 breaker.record_step(&Usage::default());
1727 breaker.record_step(&Usage::default());
1728 assert_eq!(
1729 breaker.before_step().unwrap_err().to_string(),
1730 "Circuit tripped: step budget reached (2 steps)"
1731 );
1732
1733 let mut costly = CircuitBreaker::new(&limits());
1734 costly.record_step(&Usage {
1735 cost_usd: 1.25,
1736 ..Usage::default()
1737 });
1738 assert_eq!(
1739 costly.before_step().unwrap_err().to_string(),
1740 "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
1741 );
1742
1743 let mut errors = CircuitBreaker::new(&limits());
1744 errors.record_tool_result(false).unwrap();
1745 errors.record_tool_result(true).unwrap();
1746 errors.record_tool_result(false).unwrap();
1747 assert_eq!(
1748 errors.record_tool_result(false).unwrap_err().to_string(),
1749 "Circuit tripped: aborted after 2 consecutive tool errors"
1750 );
1751 }
1752
1753 fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
1754 ToolResult {
1755 call_id: "c".to_owned(),
1756 name: "t".to_owned(),
1757 ok,
1758 content: content.to_owned(),
1759 error: error.map(str::to_owned),
1760 metadata: serde_json::Map::new(),
1761 }
1762 }
1763
1764 #[test]
1765 fn observations_keep_both_error_and_output() {
1766 assert_eq!(observation(&result(true, "data", None)), "data");
1767 assert_eq!(
1768 observation(&result(false, " out ", Some(" bad "))),
1769 "bad\nout"
1770 );
1771 assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
1772 assert_eq!(observation(&result(false, "", None)), "error");
1773 }
1774
1775 #[test]
1776 fn summaries_show_the_first_line() {
1777 assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
1778 assert_eq!(summarize(&result(true, " ", None)), "(no output)");
1779 assert_eq!(
1780 summarize(&result(false, "", Some("No such file: x\nmore"))),
1781 "error: No such file: x"
1782 );
1783 assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
1784 assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
1785 }
1786
1787 #[test]
1788 fn previews_use_python_json_and_cut_at_160_characters() {
1789 let Value::Object(short) = json!({"path": "src/main.rs"}) else {
1790 unreachable!()
1791 };
1792 assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
1793
1794 let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
1795 unreachable!()
1796 };
1797 let preview = preview_arguments(&long);
1798 assert!(preview.ends_with(" ..."));
1799 assert_eq!(preview.chars().count(), 164);
1800 }
1801
1802 #[test]
1803 fn invalid_json_is_reported_with_a_python_repr_preview() {
1804 let call = ToolCall {
1805 id: "c1".to_owned(),
1806 name: "read_file".to_owned(),
1807 arguments: serde_json::Map::new(),
1808 };
1809 let result = invalid_arguments_result(&call, "{\"path\": ");
1810 assert_eq!(
1811 result.error.as_deref(),
1812 Some(
1813 "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
1814 Call the tool again with its arguments as a single valid JSON object."
1815 )
1816 );
1817 assert!(!result.ok);
1818 assert_eq!(result.call_id, "c1");
1819 }
1820}