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::collections::HashMap;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::Arc;
53use std::time::{Duration, Instant};
54use thiserror::Error;
55
56pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
58
59pub const MAX_CONTINUATIONS: u64 = 3;
61
62pub fn continuation_notice(index: u64) -> String {
64 format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
65}
66
67pub const ANSWER_PROMPT: &str =
69 "Your last reply was empty. Give the user your answer now, as plain text.";
70
71pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
73
74pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
76
77pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
79
80pub const REASONING_LOOP_NOTICE: &str =
83 "\n[the model's reasoning was repeating itself; stopped it]\n";
84
85pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
87
88#[derive(Clone, Default)]
93pub struct CancelToken {
94 inner: Arc<CancelInner>,
95}
96
97impl std::fmt::Debug for CancelToken {
98 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 formatter
100 .debug_struct("CancelToken")
101 .field("cancelled", &self.is_cancelled())
102 .finish()
103 }
104}
105
106#[derive(Default)]
107struct CancelInner {
108 flag: AtomicBool,
109 notify: tokio::sync::Notify,
110}
111
112impl CancelToken {
113 pub fn cancel(&self) {
114 self.inner.flag.store(true, Ordering::SeqCst);
115 self.inner.notify.notify_waiters();
116 }
117
118 pub fn is_cancelled(&self) -> bool {
119 self.inner.flag.load(Ordering::SeqCst)
120 }
121
122 pub fn clear(&self) {
123 self.inner.flag.store(false, Ordering::SeqCst);
124 }
125
126 pub async fn cancelled(&self) {
128 loop {
129 let notified = self.inner.notify.notified();
130 tokio::pin!(notified);
131 notified.as_mut().enable();
133 if self.is_cancelled() {
134 return;
135 }
136 notified.await;
137 }
138 }
139}
140
141#[derive(Debug, Clone, Copy)]
148#[non_exhaustive]
149pub enum TurnEvent<'a> {
150 Text(&'a str),
152 Notice(&'a str),
156 Thinking(&'a str),
159 ToolCall { call: &'a ToolCall, text: &'a str },
161 ToolResult {
164 call: &'a ToolCall,
165 result: &'a ToolResult,
166 observation: &'a str,
167 text: &'a str,
168 },
169 Usage {
173 step: &'a crate::types::Usage,
174 session: &'a crate::types::Usage,
175 },
176 Compacted {
181 notice: &'a str,
182 summary: Option<&'a str>,
183 },
184 #[cfg(feature = "agent86ui")]
188 Ui(&'a agent86_ui::AgentMessage),
189}
190
191impl<'a> TurnEvent<'a> {
192 pub fn text(&self) -> &'a str {
194 match *self {
195 Self::Text(text)
196 | Self::Notice(text)
197 | Self::ToolCall { text, .. }
198 | Self::ToolResult { text, .. }
199 | Self::Compacted { notice: text, .. } => text,
200 Self::Thinking(_) | Self::Usage { .. } => "",
201 #[cfg(feature = "agent86ui")]
202 Self::Ui(_) => "",
203 }
204 }
205}
206
207#[derive(Debug, Clone, PartialEq, Error)]
209pub enum HarnessError {
210 #[error(transparent)]
211 Provider(#[from] ProviderError),
212
213 #[error("Circuit tripped: {0}")]
214 CircuitTripped(String),
215
216 #[error(
217 "The '{provider}' provider ended its stream for model {} without a final completion. \
218 The response was truncated; retry, or check the endpoint's streaming implementation.",
219 python_repr(model)
220 )]
221 NoFinalCompletion { provider: String, model: String },
222}
223
224impl HarnessError {
225 pub fn python_type(&self) -> &'static str {
228 match self {
229 Self::Provider(_) => "ProviderError",
230 Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
231 }
232 }
233}
234
235pub struct CircuitBreaker {
237 limits: LimitsConfig,
238 steps: u32,
239 cost_usd: f64,
240 consecutive_errors: u32,
241 started: Instant,
242}
243
244impl CircuitBreaker {
245 pub fn new(limits: &LimitsConfig) -> Self {
246 Self {
247 limits: limits.clone(),
248 steps: 0,
249 cost_usd: 0.0,
250 consecutive_errors: 0,
251 started: Instant::now(),
252 }
253 }
254
255 pub fn steps(&self) -> u32 {
256 self.steps
257 }
258
259 pub fn max_steps(&self) -> u32 {
261 self.limits.max_steps
262 }
263
264 pub fn set_max_steps(&mut self, max_steps: u32) {
266 self.limits.max_steps = max_steps;
267 }
268
269 pub fn out_of_steps(&self) -> bool {
271 self.steps >= self.limits.max_steps
272 }
273
274 pub fn before_step(&self) -> Result<(), HarnessError> {
276 let limits = &self.limits;
277 if self.steps >= limits.max_steps {
278 return Err(trip(format!(
279 "step budget reached ({} steps)",
280 limits.max_steps
281 )));
282 }
283 if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
284 return Err(trip(format!(
285 "cost cap reached (${:.4} >= ${})",
286 self.cost_usd,
287 python_float_repr(limits.max_cost_usd)
288 )));
289 }
290 let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
291 if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
292 return Err(trip(format!(
293 "wall-clock limit reached ({}s)",
294 limits.max_wall_clock_s
295 )));
296 }
297 Ok(())
298 }
299
300 pub fn record_step(&mut self, usage: &Usage) {
301 self.steps += 1;
302 self.cost_usd += usage.cost_usd;
303 }
304
305 pub fn cost(&self) -> f64 {
308 self.cost_usd
309 }
310
311 pub fn record_cost(&mut self, cost_usd: f64) {
312 self.cost_usd += cost_usd;
313 }
314
315 pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
316 if ok {
317 self.consecutive_errors = 0;
318 return Ok(());
319 }
320 self.consecutive_errors += 1;
321 if self.consecutive_errors > self.limits.max_consecutive_errors {
322 return Err(trip(format!(
323 "aborted after {} consecutive tool errors",
324 self.consecutive_errors
325 )));
326 }
327 Ok(())
328 }
329}
330
331fn trip(reason: String) -> HarnessError {
332 HarnessError::CircuitTripped(reason)
333}
334
335pub struct Harness {
337 pub provider: Arc<dyn Provider>,
340 pub router: Router,
342 pub tracer: crate::otel::Tracer,
344 pub registry: ToolRegistry,
345 pub context: ToolContext,
346 pub limits: LimitsConfig,
347 pub agents: AgentsConfig,
349 pub system: Message,
350 pub max_tokens: u32,
353 pub session_limits: crate::limits::SessionLimits,
356 pub context_window: u64,
359 pub gate: ApprovalGate,
361 pub guardrails: Guardrails,
363 pub recorder: Recorder,
365 pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
368 pub memory: Option<crate::session::SessionStore>,
371 pub cancel: CancelToken,
373 pub subagents: crate::subagent::SubagentState,
376}
377
378impl Harness {
379 pub(crate) fn system_message(&self, extra: Option<&str>) -> Message {
384 let offered = self.delegation_offered(&self.context, 0);
385 if let Some((persona, preloaded)) = self.subagents.main() {
387 return self.filtered_system(&persona, &self.context, &preloaded, offered, extra);
388 }
389 self.system_for(&self.context, offered, extra)
390 }
391
392 pub(crate) fn system_for(
396 &self,
397 ctx: &ToolContext,
398 delegation_offered: bool,
399 extra: Option<&str>,
400 ) -> Message {
401 let mut system = self.system.clone();
402 if let Some(section) = self
403 .mcp
404 .as_ref()
405 .map(|mcp| mcp.prompt_section())
406 .filter(|section| !section.is_empty())
407 {
408 system.content = format!("{}\n\n{section}", system.content);
409 }
410 if delegation_offered {
411 if let Some(section) = self.specialty_listing(ctx) {
412 system.content = format!("{}\n\n{section}", system.content);
413 }
414 }
415 if let Some(section) = ctx.secrets.prompt_section() {
416 system.content = format!("{}\n\n{section}", system.content);
417 }
418 if crate::ask::reachable(ctx) && ctx.allowed_tool(crate::ask::ASK_USER) {
421 #[cfg(feature = "agent86ui")]
422 let drawing = ctx.ui.is_some() && ctx.allowed_tool(crate::agent86ui::RENDER_UI);
423 #[cfg(not(feature = "agent86ui"))]
424 let drawing = false;
425 system.content = format!(
426 "{}\n\n{}",
427 system.content,
428 crate::ask::prompt_section(drawing)
429 );
430 }
431 #[cfg(feature = "agent86ui")]
434 if let Some(ui) = ctx.ui.as_deref() {
435 if ctx.allowed_tool(crate::agent86ui::RENDER_UI) {
436 system.content = format!("{}\n\n{}", system.content, ui.prompt_section());
437 }
438 }
439 if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
440 system.content = format!("{}\n\n{extra}", system.content);
441 }
442 system
443 }
444
445 pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
450 self.context_budget_with(
451 system,
452 specs,
453 self.active_context_window(),
454 self.output_cap(),
455 )
456 }
457
458 pub(crate) fn context_budget_with(
461 &self,
462 system: &Message,
463 specs: &[ToolSpec],
464 window: u64,
465 output_cap: u32,
466 ) -> u64 {
467 let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
468 conversation_budget(
469 window,
470 overhead,
471 self.limits.context_reserve_tokens,
472 u64::from(output_cap),
473 self.limits.max_context_tokens,
474 )
475 }
476
477 async fn compact_if_needed(
487 &self,
488 state: &mut AgentState,
489 extra_system: Option<&str>,
490 summary: &mut TurnSummary,
491 breaker: &mut CircuitBreaker,
492 protect_from: usize,
493 ) -> Option<(String, usize, Option<String>)> {
494 if self.limits.compaction != CompactionMode::Summarize {
495 return None;
496 }
497 let system = self.system_message(extra_system);
498 let budget = self.context_budget(&system, &self.registry.specs());
499 if fits(&state.messages, budget) {
500 return None;
501 }
502 let cut = compaction_cut(&state.messages, budget, KEEP_RECENT, Some(protect_from));
503 if cut == 0 {
504 return None;
507 }
508 let sid = state.session_id.clone();
509 let prefix = &state.messages[..cut];
510 let dropped_tokens = count_tokens(prefix);
511 let summarizer = self.summary_provider();
512 let request = CompletionRequest {
513 model: summarizer.model().to_owned(),
514 messages: vec![
515 message(Role::System, SUMMARY_SYSTEM_PROMPT),
516 message(Role::User, &render_transcript(prefix)),
517 ],
518 tools: Vec::new(),
519 temperature: 0.0,
520 max_tokens: Some(SUMMARY_MAX_TOKENS * 2),
522 stream: false,
523 };
524 let completion = tokio::select! {
525 biased;
526 () = self.cancel.cancelled() => return None,
528 completion = summarizer.complete(request) => completion,
529 };
530 let failed = |status: &str, error: Option<String>| {
531 let mut fields = vec![
532 ("status", json!(status)),
533 ("fallback", json!("drop")),
534 ("dropped", json!(cut)),
535 ];
536 if let Some(error) = error {
537 fields.push(("error", json!(error)));
538 }
539 self.recorder.event(&sid, "compaction", fields);
540 Some((compaction_failed_notice(cut), 0, None))
541 };
542 let completion = match completion {
543 Ok(completion) => completion,
544 Err(error) => return failed("failed", Some(format!("ProviderError: {error}"))),
545 };
546 let text = python_strip(&completion.text).to_owned();
547 if text.is_empty() {
548 return failed("empty", None);
549 }
550
551 if let Some(memory) = &self.memory {
553 let _ = memory.record_compaction(&sid, &text, prefix);
554 }
555 let before = state.messages.len();
556 let kept = state.messages.split_off(cut);
557 state.messages = apply_summary(&text, kept);
558 summary.compactions += 1;
559 summary.add_usage(&completion.usage);
560 breaker.record_cost(completion.usage.cost_usd);
561 self.recorder.event(
562 &sid,
563 "compaction",
564 vec![
565 ("status", json!("ok")),
566 ("dropped", json!(cut)),
567 ("dropped_tokens", json!(dropped_tokens)),
568 (
569 "summary_tokens",
570 json!(count_tokens(&[message(Role::User, &text)])),
571 ),
572 ("kept", json!(state.messages.len())),
573 ("model", json!(summarizer.model())),
574 ],
575 );
576 if let Some(memory) = &self.memory {
579 let _ = memory.persist(state);
580 }
581 Some((
582 compacted_notice(cut),
583 before - state.messages.len(),
584 Some(text),
585 ))
586 }
587
588 pub async fn run_turn(
595 &self,
596 state: &mut AgentState,
597 goal: &str,
598 on_text: impl FnMut(&str),
599 ) -> Result<String, HarnessError> {
600 self.run_turn_as(state, goal, goal, on_text).await
601 }
602
603 pub async fn run_turn_as(
607 &self,
608 state: &mut AgentState,
609 user_text: &str,
610 display_text: &str,
611 mut on_text: impl FnMut(&str),
612 ) -> Result<String, HarnessError> {
613 self.run_turn_events(state, user_text, display_text, |event| {
614 on_text(event.text())
615 })
616 .await
617 }
618
619 pub async fn run_turn_events(
623 &self,
624 state: &mut AgentState,
625 user_text: &str,
626 display_text: &str,
627 on_event: impl FnMut(TurnEvent<'_>),
628 ) -> Result<String, HarnessError> {
629 self.run_turn_with(state, user_text, display_text, None, on_event)
630 .await
631 }
632
633 pub async fn run_skill_turn(
640 &self,
641 state: &mut AgentState,
642 skill: &Arc<crate::skills::Skill>,
643 task: &str,
644 display_text: &str,
645 on_event: impl FnMut(TurnEvent<'_>),
646 ) -> Result<String, HarnessError> {
647 let user_text = crate::skills::skill_request(skill, task);
648 self.run_turn_with(state, &user_text, display_text, Some(skill), on_event)
649 .await
650 }
651
652 async fn run_turn_with(
653 &self,
654 state: &mut AgentState,
655 user_text: &str,
656 display_text: &str,
657 skill: Option<&Arc<crate::skills::Skill>>,
658 on_event: impl FnMut(TurnEvent<'_>),
659 ) -> Result<String, HarnessError> {
660 self.cancel.clear();
662 self.context.clear_skill();
667 if let Some(skill) = skill {
668 self.context.activate_skill(skill);
669 }
670 let started = Instant::now();
671 let mut span = self.tracer.start(
673 "turn",
674 vec![
675 ("session.id", json!(state.session_id)),
676 (
677 "gen_ai.request.model",
678 json!(self.active_provider().model()),
679 ),
680 ],
681 );
682 let mut summary = TurnSummary::default();
683 let secrets = &self.context.secrets;
686 let (user_text, display_text) = (secrets.redact(user_text), secrets.redact(display_text));
687 let result = self
688 .turn(state, &user_text, &display_text, &mut summary, on_event)
689 .await;
690 self.context.clear_skill();
691 summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
692 state.last_turn = Some(summary);
693 if let Err(error) = &result {
694 state.phase = AgentPhase::Error;
695 let reason = match error {
696 HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
697 HarnessError::Provider(detail) => {
698 format!("provider stream failed: ProviderError: {detail}")
699 }
700 HarnessError::NoFinalCompletion { .. } => {
701 "provider stream ended without a final completion".to_owned()
702 }
703 };
704 self.recorder.event(
705 &state.session_id,
706 "turn_end",
707 vec![("status", json!("error")), ("reason", json!(reason))],
708 );
709 }
710 span.set(turn_attributes(state, self.active_provider().model()));
713 if let Err(error) = &result {
714 span.fail(error.python_type(), &error.to_string());
715 }
716 self.tracer.end(span);
717 result
718 }
719
720 async fn turn(
721 &self,
722 state: &mut AgentState,
723 goal: &str,
724 display_text: &str,
725 summary: &mut TurnSummary,
726 mut on_event: impl FnMut(TurnEvent<'_>),
727 ) -> Result<String, HarnessError> {
728 let mut output = String::new();
729 let mut emit = |event: TurnEvent<'_>| {
730 output.push_str(event.text());
731 on_event(event);
732 };
733
734 let sid = state.session_id.clone();
735 self.recorder
736 .event(&sid, "turn_start", vec![("task", json!(display_text))]);
737
738 let report = self.guardrails.inspect_ingress(goal);
740 if report.flagged() {
741 self.recorder.event(
742 &sid,
743 "guardrail",
744 vec![
745 ("stage", json!("ingress_input")),
746 ("findings", json!(report.summary())),
747 ],
748 );
749 if self.guardrails.should_block(&report) {
750 let refusal = format!(
751 "Refused: input tripped the ingress guardrail ({}).",
752 report.summary()
753 );
754 state.messages.push(message(Role::User, goal));
755 state.messages.push(message(Role::Assistant, &refusal));
756 state.phase = AgentPhase::Error;
757 self.recorder
758 .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
759 emit(TurnEvent::Text(&refusal));
760 return Ok(output);
761 }
762 emit(TurnEvent::Notice(&format!(
763 "[guardrail] input flagged: {}\n",
764 report.summary()
765 )));
766 }
767
768 let buffering = self.guardrails.egress == EgressMode::Redact;
771
772 self.route(goal, &sid)?;
774 let provider = self.active_provider();
775
776 let recall_note = self
778 .memory
779 .as_ref()
780 .and_then(|memory| memory.recall_note(goal));
781 let time = time_note(&jiff::ZonedDateTime::now());
783 let recall_note = Some(match recall_note {
784 Some(recalled) => format!("{time}\n\n{recalled}"),
785 None => time,
786 });
787 let mut turn_start = state.messages.len();
790 state.messages.push(message(Role::User, goal));
791 let mut limits = self.limits.clone();
792 limits.max_steps = self.max_steps();
793 let mut breaker = CircuitBreaker::new(&limits);
794 let mut broken_streak = BrokenStreak::default();
795 let mut continuation_start: Option<usize> = None;
797 let mut continuation_parts: Vec<String> = Vec::new();
798 let mut nudged = false;
802 let mut ask_again = false;
803 let mut unanswered_thinking = String::new();
804
805 loop {
806 if self.cancel.is_cancelled() {
809 self.cancelled(state, breaker.steps(), &mut emit);
810 return Ok(output);
811 }
812 if breaker.out_of_steps() {
814 match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
815 Some(raised) => breaker.set_max_steps(raised),
816 None if self.cancel.is_cancelled() => {
818 self.cancelled(state, breaker.steps(), &mut emit);
819 return Ok(output);
820 }
821 None => {}
822 }
823 }
824 breaker.before_step()?;
825
826 if let Some((notice, removed, compacted)) = self
829 .compact_if_needed(
830 state,
831 recall_note.as_deref(),
832 summary,
833 &mut breaker,
834 turn_start,
835 )
836 .await
837 {
838 turn_start -= removed;
841 if let Some(start) = continuation_start.as_mut() {
842 *start -= removed;
843 }
844 emit(TurnEvent::Compacted {
847 notice: ¬ice,
848 summary: compacted.as_deref(),
849 });
850 }
851
852 let mut completion = {
853 let system = self.system_message(recall_note.as_deref());
854 let mut tools = self.registry.specs();
855 tools.retain(|spec| self.context.scope_allows(&spec.name));
857 let budget = self.context_budget(&system, &tools);
858 let conversation = fit(&state.messages, budget);
859 let mut request_messages = Vec::with_capacity(conversation.len() + 1);
860 request_messages.push(system);
861 request_messages.extend(conversation.iter().cloned());
862 if std::mem::take(&mut ask_again) {
863 request_messages.push(message(Role::User, ANSWER_PROMPT));
864 }
865 let request = CompletionRequest {
866 model: provider.model().to_owned(),
867 messages: request_messages,
868 tools,
869 temperature: 0.0,
870 max_tokens: Some(self.output_cap()),
871 stream: true,
872 };
873 let mut span = self.tracer.start(
875 "model_call",
876 vec![
877 ("gen_ai.system", json!(provider.name())),
878 ("gen_ai.request.model", json!(provider.model())),
879 ("agent86.step", json!(breaker.steps() + 1)),
880 ],
881 );
882 let mut stream = provider.stream(request);
883 let mut completion = None;
884 let mut buffered = String::new();
885 let mut redactor = StreamRedactor::default();
888 let mut thinking_redactor = StreamRedactor::default();
889 loop {
890 let next = tokio::select! {
893 biased;
894 () = self.cancel.cancelled() => None,
895 delta = stream.next() => Some(delta),
896 };
897 let Some(Some(delta)) = next else { break };
898 let delta = match delta {
899 Ok(delta) => delta,
900 Err(error) => {
901 span.set(model_call_attributes(None));
902 span.fail("ProviderError", &error.to_string());
903 self.tracer.end(span);
904 return Err(error.into());
905 }
906 };
907 if !delta.thinking.is_empty() && !buffering {
910 let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
911 if !shown.is_empty() {
912 emit(TurnEvent::Thinking(&shown));
913 }
914 }
915 if !delta.text.is_empty() {
916 if buffering {
917 buffered.push_str(&delta.text);
918 } else {
919 let shown = redactor.push(&self.context.secrets, &delta.text);
920 if !shown.is_empty() {
921 emit(TurnEvent::Text(&shown));
922 }
923 }
924 }
925 if delta.done && delta.completion.is_some() {
926 completion = delta.completion;
927 }
928 }
929 drop(stream);
930 let held = thinking_redactor.finish(&self.context.secrets);
931 if !held.is_empty() {
932 emit(TurnEvent::Thinking(&held));
933 }
934 let held = redactor.finish(&self.context.secrets);
935 if !held.is_empty() {
936 emit(TurnEvent::Text(&held));
937 }
938 span.set(model_call_attributes(completion.as_ref()));
939 self.tracer.end(span);
940 if self.cancel.is_cancelled() {
941 let partial = self
943 .guardrails
944 .inspect_egress(&self.context.secrets.redact(&buffered))
945 .1;
946 if !partial.is_empty() {
947 emit(TurnEvent::Text(&partial));
948 }
949 self.cancelled(state, breaker.steps(), &mut emit);
950 return Ok(output);
951 }
952 completion.ok_or_else(|| HarnessError::NoFinalCompletion {
953 provider: provider.name().to_owned(),
954 model: provider.model().to_owned(),
955 })?
956 };
957
958 breaker.record_step(&completion.usage);
959 summary.steps = u64::from(breaker.steps());
960 summary.add_usage(&completion.usage);
961 emit(TurnEvent::Usage {
964 step: &completion.usage,
965 session: &(state.usage + completion.usage),
966 });
967 let names: Vec<&str> = completion
968 .tool_calls
969 .iter()
970 .map(|call| call.name.as_str())
971 .collect();
972 self.recorder.event(
973 &sid,
974 "model_call",
975 vec![
976 ("step", json!(breaker.steps())),
977 ("model", json!(provider.model())),
978 ("input_tokens", json!(completion.usage.input_tokens)),
979 ("output_tokens", json!(completion.usage.output_tokens)),
980 ("cost_usd", json!(completion.usage.cost_usd)),
981 ("stop_reason", json!(completion.stop_reason)),
982 ("tool_calls", json!(names)),
983 ],
984 );
985
986 if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
987 emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
988 }
989 let stopped = completion
992 .stop_reason
993 .as_deref()
994 .and_then(|reason| reason.strip_prefix(crate::provider::google::STOPPED_PREFIX))
995 .map(str::to_owned);
996 if let Some(reason) = &stopped {
997 emit(TurnEvent::Notice(&format!(
998 "\n[{} stopped the reply: {reason}]\n",
999 provider.name()
1000 )));
1001 }
1002
1003 let mut from_thinking = false;
1009 if completion.tool_calls.is_empty()
1010 && completion.stop_reason.as_deref() != Some("max_tokens")
1011 && stopped.is_none()
1012 && completion.text.trim().is_empty()
1013 && continuation_start.is_none()
1014 {
1015 if !completion.thinking.trim().is_empty() {
1016 unanswered_thinking = std::mem::take(&mut completion.thinking);
1017 }
1018 if !nudged && !breaker.out_of_steps() {
1019 nudged = true;
1020 ask_again = true;
1021 self.recorder.event(
1022 &sid,
1023 "empty_answer",
1024 vec![
1025 ("step", json!(breaker.steps())),
1026 ("model", json!(provider.model())),
1027 ("thinking_chars", json!(unanswered_thinking.chars().count())),
1028 ],
1029 );
1030 record_step(
1031 state,
1032 Step {
1033 index: state.steps.len() as u64 + 1,
1034 phase: AgentPhase::Execute,
1035 thought: String::new(),
1036 tool_calls: Vec::new(),
1037 results: Vec::new(),
1038 usage: completion.usage,
1039 },
1040 );
1041 self.checkpoint(state);
1042 emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1043 continue;
1044 }
1045 if unanswered_thinking.trim().is_empty() {
1046 emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1047 if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1050 emit(TurnEvent::Notice(&format!(
1051 "{}\n",
1052 crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1053 )));
1054 }
1055 } else {
1056 completion.text = std::mem::take(&mut unanswered_thinking);
1057 from_thinking = true;
1058 emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1059 }
1060 }
1061
1062 let answer = self.context.secrets.redact(&completion.text);
1065 let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1066 let text = if buffering {
1067 if !redacted.is_empty() {
1068 emit(TurnEvent::Text(&redacted));
1069 }
1070 redacted
1071 } else {
1072 if from_thinking {
1074 emit(TurnEvent::Text(&answer));
1075 }
1076 answer
1077 };
1078 if egress.flagged() {
1079 self.recorder.event(
1080 &sid,
1081 "guardrail",
1082 vec![
1083 ("stage", json!("egress")),
1084 ("findings", json!(egress.summary())),
1085 ],
1086 );
1087 emit(TurnEvent::Notice(&format!(
1088 "\n[guardrail] output flagged: {}\n",
1089 egress.summary()
1090 )));
1091 }
1092 let mut tool_calls = completion.tool_calls;
1093 let repairs = self.repair_broken_calls(&mut tool_calls, &sid);
1095 self.scan_tool_arguments(&tool_calls, &sid);
1096 let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1097 if cut_off
1102 && tool_calls.is_empty()
1103 && text.trim().is_empty()
1104 && continuation_start.is_none()
1105 {
1106 let cap = self.output_cap();
1107 if self
1108 .raise_limit(LimitKind::Output, None, &sid, cap, false)
1109 .is_some()
1110 {
1111 record_step(
1112 state,
1113 Step {
1114 index: state.steps.len() as u64 + 1,
1115 phase: AgentPhase::Execute,
1116 thought: String::new(),
1117 tool_calls: Vec::new(),
1118 results: Vec::new(),
1119 usage: completion.usage,
1120 },
1121 );
1122 self.checkpoint(state);
1123 continue;
1124 }
1125 }
1126 let mut step = Step {
1127 index: state.steps.len() as u64 + 1,
1128 phase: AgentPhase::Execute,
1129 thought: text.clone(),
1130 tool_calls: tool_calls.clone(),
1131 results: Vec::new(),
1132 usage: completion.usage,
1133 };
1134 state.messages.push(Message {
1135 tool_calls: tool_calls.clone(),
1136 ..message(Role::Assistant, &text)
1137 });
1138
1139 if tool_calls.is_empty() {
1140 if cut_off && summary.continuations < MAX_CONTINUATIONS {
1141 summary.continuations += 1;
1142 continuation_start.get_or_insert(state.messages.len() - 1);
1143 continuation_parts.push(text);
1144 state.messages.push(message(Role::User, CONTINUE_PROMPT));
1145 record_step(state, step);
1146 self.checkpoint(state);
1147 self.recorder.event(
1148 &sid,
1149 "continuation",
1150 vec![
1151 ("index", json!(summary.continuations)),
1152 ("step", json!(breaker.steps())),
1153 ("model", json!(provider.model())),
1154 (
1155 "chars",
1156 json!(continuation_parts
1157 .last()
1158 .map_or(0, |part| part.chars().count())),
1159 ),
1160 ],
1161 );
1162 emit(TurnEvent::Notice(&continuation_notice(
1163 summary.continuations,
1164 )));
1165 continue;
1166 }
1167 if let Some(start) = continuation_start {
1168 continuation_parts.push(text);
1170 let joined = continuation_parts.concat();
1171 state.messages.truncate(start);
1172 state.messages.push(message(Role::Assistant, &joined));
1173 step.thought = joined;
1174 }
1175 let outcome = step.thought.clone();
1176 record_step(state, step);
1177 state.phase = AgentPhase::Done;
1178 self.recorder.event(
1179 &sid,
1180 "turn_end",
1181 vec![
1182 ("status", json!("done")),
1183 ("steps", json!(breaker.steps())),
1184 ("continuations", json!(summary.continuations)),
1185 ],
1186 );
1187 if let Some(memory) = &self.memory {
1188 let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1190 }
1191 return Ok(output);
1192 }
1193
1194 continuation_start = None;
1196 continuation_parts.clear();
1197
1198 if self.cancel.is_cancelled() {
1202 for call in &tool_calls {
1203 let result = not_executed(call, "cancelled");
1204 state.messages.push(Message {
1205 tool_call_id: Some(call.id.clone()),
1206 name: Some(call.name.clone()),
1207 ..message(Role::Tool, &observation(&result))
1208 });
1209 step.results.push(result);
1210 }
1211 record_step(state, step);
1212 self.cancelled(state, breaker.steps(), &mut emit);
1213 return Ok(output);
1214 }
1215
1216 for call in &tool_calls {
1218 let text = format!(
1219 "\n[tool] {}({})\n",
1220 call.name,
1221 preview_arguments(&call.arguments)
1222 );
1223 emit(TurnEvent::ToolCall { call, text: &text });
1224 }
1225 let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1226 for notice in self.take_notices() {
1230 emit(TurnEvent::Notice(&format!("{notice}\n")));
1231 }
1232 for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1233 summary.tool_calls += 1;
1234 #[cfg(feature = "agent86ui")]
1237 let result = {
1238 let mut result = result;
1239 let (drawn, trace) = crate::agent86ui::take_drawn(&mut result.metadata);
1240 for message in &drawn {
1241 emit(TurnEvent::Ui(message));
1242 }
1243 if let Some(Value::Object(fields)) = trace {
1244 let fields: Vec<(&str, Value)> = fields
1247 .iter()
1248 .map(|(key, value)| (key.as_str(), value.clone()))
1249 .collect();
1250 self.recorder.event(&sid, "ui_render", fields);
1251 }
1252 match crate::agent86ui::take_wait(&mut result.metadata) {
1255 Some(surfaces) => self.ui_wait(call, result, surfaces, &sid),
1256 None => result,
1257 }
1258 };
1259 let result = self.ask_questions(call, result, &sid, &mut emit);
1262 let result = self.annotate_broken_json(call, result, &repairs, &mut broken_streak);
1263 summary.add_usage(&delegated);
1266 step.usage = step.usage + delegated;
1267 breaker.record_cost(delegated.cost_usd);
1268 let (content, findings) = self.guardrails.observe(observation(&result));
1269 if let Some(findings) = findings {
1270 self.recorder.event(
1271 &sid,
1272 "guardrail",
1273 vec![
1274 ("stage", json!("observation")),
1275 ("tool", json!(call.name)),
1276 ("findings", json!(findings)),
1277 ],
1278 );
1279 }
1280 emit(TurnEvent::ToolResult {
1281 call,
1282 result: &result,
1283 observation: &content,
1284 text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1285 });
1286 state.messages.push(Message {
1287 tool_call_id: Some(call.id.clone()),
1288 name: Some(call.name.clone()),
1289 ..message(Role::Tool, &content)
1290 });
1291 let ok = result.ok;
1292 step.results.push(result);
1293 if let Err(tripped) = breaker.record_tool_result(ok) {
1294 record_step(state, step);
1295 return Err(tripped);
1296 }
1297 }
1298 record_step(state, step);
1301 self.checkpoint(state);
1302 if self.cancel.is_cancelled() {
1303 self.cancelled(state, breaker.steps(), &mut emit);
1304 return Ok(output);
1305 }
1306 }
1307 }
1308
1309 fn checkpoint(&self, state: &mut AgentState) {
1316 state.phase = AgentPhase::Execute;
1317 if let Some(memory) = &self.memory {
1318 let _ = memory.persist(state);
1319 }
1320 }
1321
1322 fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
1326 state.phase = AgentPhase::Error;
1327 self.recorder.event(
1328 &state.session_id,
1329 "turn_end",
1330 vec![
1331 ("status", json!("cancelled")),
1332 ("reason", json!("cancelled")),
1333 ("steps", json!(steps)),
1334 ],
1335 );
1336 emit(TurnEvent::Notice(CANCELLED_NOTICE));
1337 }
1338
1339 async fn execute_batch(
1353 &self,
1354 calls: &[ToolCall],
1355 sid: &str,
1356 spent: f64,
1357 ) -> Vec<(ToolResult, Usage)> {
1358 let eligible = calls
1359 .iter()
1360 .filter(|call| self.parallel_eligible(call))
1361 .count();
1362 let specialty: Vec<bool> = calls
1363 .iter()
1364 .map(|call| self.is_specialty_delegation(call))
1365 .collect();
1366 let any_specialty = specialty.contains(&true);
1367 if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
1368 let mut results = Vec::with_capacity(calls.len());
1370 for call in calls {
1371 results.push(if self.cancel.is_cancelled() {
1372 (not_executed(call, "cancelled"), Usage::default())
1373 } else {
1374 self.execute_tool(call, sid).await
1375 });
1376 }
1377 return results;
1378 }
1379
1380 let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
1381 let mut may_parallel = Vec::with_capacity(calls.len());
1382 for call in calls {
1383 let (result, parallel) = self.resolve_call(call, sid);
1384 settled.push(result.map(|result| (result, Usage::default())));
1385 may_parallel.push(parallel);
1386 }
1387 let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
1388 let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
1389 let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
1390
1391 if reads.len() > 1 {
1392 let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
1393 let handles: Vec<_> = reads
1394 .iter()
1395 .map(|&index| {
1396 (
1397 index,
1398 scope.spawn(move || self.dispatch(&calls[index], sid)),
1399 )
1400 })
1401 .collect();
1402 handles
1403 .into_iter()
1404 .map(|(index, handle)| {
1405 let result = handle
1406 .join()
1407 .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
1408 (index, result)
1409 })
1410 .collect()
1411 });
1412 for (index, result) in collected {
1413 settled[index] = Some((result, Usage::default()));
1414 }
1415 } else {
1416 for &index in &reads {
1417 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1418 }
1419 }
1420 let mut next = 0;
1424 while next < writes.len() {
1425 let index = writes[next];
1426 let run_end = writes[next..]
1427 .iter()
1428 .position(|&index| !specialty[index])
1429 .map_or(writes.len(), |offset| next + offset);
1430 if specialty[index] && run_end - next > 1 {
1431 let group: Vec<usize> = writes[next..run_end].to_vec();
1432 let results = if self.cancel.is_cancelled() {
1433 group
1434 .iter()
1435 .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
1436 .collect()
1437 } else {
1438 let members: Vec<&ToolCall> =
1439 group.iter().map(|&index| &calls[index]).collect();
1440 self.fan_out(&members, sid, spent)
1441 };
1442 for (index, result) in group.into_iter().zip(results) {
1443 settled[index] = Some(result);
1444 }
1445 next = run_end;
1446 } else {
1447 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1448 next += 1;
1449 }
1450 }
1451
1452 settled
1453 .into_iter()
1454 .zip(calls)
1455 .map(|(result, call)| {
1456 result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
1457 })
1458 .collect()
1459 }
1460
1461 fn parallel_eligible(&self, call: &ToolCall) -> bool {
1464 call.invalid_arguments().is_none()
1465 && self
1466 .registry
1467 .get(&call.name)
1468 .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
1469 }
1470
1471 fn resolve_call(&self, call: &ToolCall, sid: &str) -> (Option<ToolResult>, bool) {
1480 let settled = |result: ToolResult| {
1481 self.record_tool_call(call, &result, sid);
1482 (Some(result), false)
1483 };
1484 if let Some(raw) = call.invalid_arguments() {
1485 return settled(invalid_arguments_result(call, raw));
1486 }
1487 let Some(tool) = self.registry.get(&call.name) else {
1488 return settled(self.registry.dispatch(call, &self.context));
1490 };
1491 if !self.context.scope_allows(&call.name) {
1494 return settled(self.registry.dispatch(call, &self.context));
1495 }
1496 let decision = self.gate.decide(tool.as_ref(), call, &self.context);
1497 if !decision.approved {
1498 return settled(not_executed(call, decision.reason));
1499 }
1500 (None, !tool.side_effecting() && tool.parallel_safe())
1501 }
1502
1503 async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1504 if self.cancel.is_cancelled() {
1505 (not_executed(call, "cancelled"), Usage::default())
1506 } else {
1507 self.dispatch_call(call, sid).await
1508 }
1509 }
1510
1511 async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1514 let request = match self.delegation(call, &self.context) {
1515 Some(request) => request,
1516 None => return (self.dispatch(call, sid), Usage::default()),
1517 };
1518 let mut span = self.tool_span(call);
1519 let (result, usage) = match request {
1520 Ok(request) => self.delegate(call, request, 1, &self.context).await,
1521 Err(invalid) => (invalid, Usage::default()),
1522 };
1523 span.set(vec![("tool.ok", json!(result.ok))]);
1524 self.tracer.end(span);
1525 self.record_tool_call(call, &result, sid);
1526 (result, usage)
1527 }
1528
1529 fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
1531 let mut span = self.tool_span(call);
1532 let result = self.registry.dispatch(call, &self.context);
1533 span.set(vec![("tool.ok", json!(result.ok))]);
1534 self.tracer.end(span);
1535 self.record_tool_call(call, &result, sid);
1536 result
1537 }
1538
1539 pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
1541 self.tracer.start(
1542 "tool_call",
1543 vec![
1544 ("tool.name", json!(call.name)),
1545 ("gen_ai.tool.name", json!(call.name)),
1546 ],
1547 )
1548 }
1549
1550 pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1551 self.recorder.event(
1552 sid,
1553 "tool_call",
1554 vec![
1555 ("tool", json!(call.name)),
1556 ("ok", json!(result.ok)),
1557 ("arguments", Value::Object(call.arguments.clone())),
1558 ("error", json!(result.error)),
1559 ],
1560 );
1561 self.record_repair(call, result, sid);
1562 }
1563
1564 pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1567 if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
1568 self.recorder.event(
1569 sid,
1570 "tool_args_repaired",
1571 vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
1572 );
1573 }
1574 }
1575
1576 pub(crate) fn repair_broken_calls(
1584 &self,
1585 calls: &mut [ToolCall],
1586 sid: &str,
1587 ) -> HashMap<String, String> {
1588 let mut notes = HashMap::new();
1589 for call in calls.iter_mut() {
1590 let Some(raw) = call.invalid_arguments() else {
1591 continue;
1592 };
1593 let Some((arguments, dropped)) = crate::broken_json::drop_unmatched_closers(raw) else {
1594 continue;
1595 };
1596 self.recorder.event(
1597 sid,
1598 "tool_args_repaired",
1599 vec![
1600 ("tool", json!(call.name)),
1601 (
1602 "dropped",
1603 json!(dropped
1604 .iter()
1605 .map(|(at, closer)| json!({"at": at, "char": closer.to_string()}))
1606 .collect::<Vec<_>>()),
1607 ),
1608 ],
1609 );
1610 notes.insert(call.id.clone(), repair_note(&dropped));
1611 call.arguments = arguments;
1612 }
1613 notes
1614 }
1615
1616 pub(crate) fn annotate_broken_json(
1621 &self,
1622 call: &ToolCall,
1623 result: ToolResult,
1624 repairs: &HashMap<String, String>,
1625 streak: &mut BrokenStreak,
1626 ) -> ToolResult {
1627 let mut result = result;
1628 if let Some(note) = repairs.get(&call.id) {
1629 append_note(&mut result, note);
1630 }
1631 if let Some(count) = streak.observe(call) {
1632 let mut advice = format!(
1633 "{count} calls in a row to {} have sent arguments that do not parse. Long, \
1634 deeply nested arguments break most often: send less in each call.",
1635 call.name
1636 );
1637 if let Some(hint) = self
1638 .registry
1639 .get(&call.name)
1640 .and_then(|tool| tool.retry_hint().map(str::to_owned))
1641 {
1642 advice.push(' ');
1643 advice.push_str(&hint);
1644 }
1645 append_note(&mut result, &advice);
1646 }
1647 result
1648 }
1649
1650 fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
1653 if self.guardrails.egress == EgressMode::Off {
1654 return;
1655 }
1656 for call in calls {
1657 let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
1658 let (report, _) = self.guardrails.inspect_egress(&payload);
1659 if report.flagged() {
1660 self.recorder.event(
1661 sid,
1662 "guardrail",
1663 vec![
1664 ("stage", json!("egress_tool_args")),
1665 ("tool", json!(call.name)),
1666 ("findings", json!(report.summary())),
1667 ],
1668 );
1669 }
1670 }
1671 }
1672
1673 async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1675 match self.resolve_call(call, sid) {
1676 (Some(result), _) => (result, Usage::default()),
1677 (None, _) => self.dispatch_call(call, sid).await,
1678 }
1679 }
1680}
1681
1682#[derive(Debug, Default)]
1685pub(crate) struct BrokenStreak(HashMap<String, u32>);
1686
1687impl BrokenStreak {
1688 fn observe(&mut self, call: &ToolCall) -> Option<u32> {
1692 let count = self.0.entry(call.name.clone()).or_default();
1693 if call.invalid_arguments().is_none() {
1694 *count = 0;
1695 return None;
1696 }
1697 *count += 1;
1698 (*count >= 2).then_some(*count)
1699 }
1700}
1701
1702fn repair_note(dropped: &[(usize, char)]) -> String {
1704 let closers: Vec<String> = dropped
1705 .iter()
1706 .map(|(at, closer)| format!("`{closer}` at character {at}"))
1707 .collect();
1708 let noun = if dropped.len() == 1 {
1709 "closer"
1710 } else {
1711 "closers"
1712 };
1713 format!(
1714 "Note: these arguments were not valid JSON. agent86 dropped the unmatched {noun} {}, \
1715 which matched nothing, and ran the call with the rest. Check next time that every \
1716 bracket closes in order.",
1717 closers.join(", ")
1718 )
1719}
1720
1721fn append_note(result: &mut ToolResult, note: &str) {
1724 let text = if result.ok {
1725 &mut result.content
1726 } else {
1727 result.error.get_or_insert_with(String::new)
1728 };
1729 if !text.is_empty() {
1730 text.push_str("\n\n");
1731 }
1732 text.push_str(note);
1733}
1734
1735pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
1737 ToolResult {
1738 call_id: call.id.clone(),
1739 name: call.name.clone(),
1740 ok: false,
1741 content: String::new(),
1742 error: Some(format!("Not executed: {reason}.")),
1743 metadata: serde_json::Map::new(),
1744 }
1745}
1746
1747fn model_call_attributes(
1749 completion: Option<&crate::types::Completion>,
1750) -> Vec<(&'static str, Value)> {
1751 let Some(completion) = completion else {
1752 return vec![("agent86.completed", json!(false))];
1753 };
1754 let finish = completion
1755 .stop_reason
1756 .as_deref()
1757 .filter(|reason| !reason.is_empty())
1758 .map_or(Value::Null, |reason| json!([reason]));
1759 vec![
1760 ("agent86.completed", json!(true)),
1761 (
1762 "gen_ai.usage.input_tokens",
1763 json!(completion.usage.input_tokens),
1764 ),
1765 (
1766 "gen_ai.usage.output_tokens",
1767 json!(completion.usage.output_tokens),
1768 ),
1769 ("gen_ai.response.finish_reasons", finish),
1770 ("agent86.cost_usd", json!(completion.usage.cost_usd)),
1771 ("agent86.tool_calls", json!(completion.tool_calls.len())),
1772 ]
1773}
1774
1775fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
1778 let mut attributes = vec![("gen_ai.request.model", json!(model))];
1779 if let Some(summary) = &state.last_turn {
1780 attributes.extend([
1781 ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
1782 ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
1783 ("agent86.cost_usd", json!(summary.cost_usd)),
1784 ("agent86.steps", json!(summary.steps)),
1785 ("agent86.tool_calls", json!(summary.tool_calls)),
1786 ("agent86.duration_s", json!(summary.duration_s)),
1787 (
1788 "agent86.phase",
1789 serde_json::to_value(state.phase).unwrap_or(Value::Null),
1790 ),
1791 ]);
1792 }
1793 attributes
1794}
1795
1796fn record_step(state: &mut AgentState, step: Step) {
1798 state.usage = state.usage + step.usage;
1799 state.steps.push(step);
1800}
1801
1802fn message(role: Role, content: &str) -> Message {
1803 Message {
1804 role,
1805 content: content.to_owned(),
1806 tool_calls: Vec::new(),
1807 tool_call_id: None,
1808 name: None,
1809 }
1810}
1811
1812pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
1818 let preview = truncate_chars(raw, 200);
1819 let mut error = format!(
1820 "invalid JSON in tool arguments: {} could not be parsed. \
1821 Call the tool again with its arguments as a single valid JSON object.",
1822 python_repr(&preview)
1823 );
1824 if let Some(location) = crate::broken_json::describe(raw) {
1825 error.push('\n');
1826 error.push_str(&location);
1827 }
1828 ToolResult {
1829 call_id: call.id.clone(),
1830 name: call.name.clone(),
1831 ok: false,
1832 content: String::new(),
1833 error: Some(error),
1834 metadata: serde_json::Map::new(),
1835 }
1836}
1837
1838pub fn observation(result: &ToolResult) -> String {
1841 if result.ok {
1842 return result.content.clone();
1843 }
1844 let error = result.error.as_deref().unwrap_or_default().trim();
1845 let body = result.content.trim();
1846 match (error.is_empty(), body.is_empty()) {
1847 (false, false) => format!("{error}\n{body}"),
1848 (false, true) => error.to_owned(),
1849 (true, false) => body.to_owned(),
1850 (true, true) => "error".to_owned(),
1851 }
1852}
1853
1854pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
1856 let text = python_json_dumps(&Value::Object(arguments.clone()), false);
1857 truncate_chars(&text, 160)
1858}
1859
1860pub fn summarize(result: &ToolResult) -> String {
1862 if !result.ok {
1863 let error = result.error.as_deref().unwrap_or_default().trim();
1864 let content = result.content.trim();
1865 let detail = [error, content, "(failed)"]
1866 .into_iter()
1867 .find(|text| !text.is_empty())
1868 .unwrap_or("(failed)");
1869 return format!("error: {}", first_chars(first_line(detail), 160));
1870 }
1871 let content = result.content.trim();
1872 let head = if content.is_empty() {
1873 "(no output)"
1874 } else {
1875 first_line(content)
1876 };
1877 first_chars(head, 160)
1878}
1879
1880fn first_line(text: &str) -> &str {
1882 let is_break = |c: char| {
1883 matches!(
1884 c,
1885 '\n' | '\r'
1886 | '\u{b}'
1887 | '\u{c}'
1888 | '\u{1c}'
1889 | '\u{1d}'
1890 | '\u{1e}'
1891 | '\u{85}'
1892 | '\u{2028}'
1893 | '\u{2029}'
1894 )
1895 };
1896 text.split(is_break).next().unwrap_or_default()
1897}
1898
1899fn first_chars(text: &str, limit: usize) -> String {
1900 text.chars().take(limit).collect()
1901}
1902
1903fn truncate_chars(text: &str, limit: usize) -> String {
1905 if text.chars().count() <= limit {
1906 text.to_owned()
1907 } else {
1908 format!("{} ...", first_chars(text, limit))
1909 }
1910}
1911
1912#[cfg(test)]
1913mod tests {
1914 use super::*;
1915 use serde_json::json;
1916
1917 fn limits() -> LimitsConfig {
1918 LimitsConfig {
1919 max_steps: 2,
1920 max_cost_usd: 1.0,
1921 max_wall_clock_s: 900,
1922 max_consecutive_errors: 1,
1923 max_context_tokens: 0,
1924 max_output_tokens: 8192,
1925 context_reserve_tokens: 4096,
1926 compaction: CompactionMode::Summarize,
1927 parallel_tools: true,
1928 tool_timeout_s: 60,
1929 }
1930 }
1931
1932 #[test]
1933 fn the_breaker_trips_on_steps_cost_and_error_streaks() {
1934 let mut breaker = CircuitBreaker::new(&limits());
1935 breaker.before_step().unwrap();
1936 breaker.record_step(&Usage::default());
1937 breaker.record_step(&Usage::default());
1938 assert_eq!(
1939 breaker.before_step().unwrap_err().to_string(),
1940 "Circuit tripped: step budget reached (2 steps)"
1941 );
1942
1943 let mut costly = CircuitBreaker::new(&limits());
1944 costly.record_step(&Usage {
1945 cost_usd: 1.25,
1946 ..Usage::default()
1947 });
1948 assert_eq!(
1949 costly.before_step().unwrap_err().to_string(),
1950 "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
1951 );
1952
1953 let mut errors = CircuitBreaker::new(&limits());
1954 errors.record_tool_result(false).unwrap();
1955 errors.record_tool_result(true).unwrap();
1956 errors.record_tool_result(false).unwrap();
1957 assert_eq!(
1958 errors.record_tool_result(false).unwrap_err().to_string(),
1959 "Circuit tripped: aborted after 2 consecutive tool errors"
1960 );
1961 }
1962
1963 fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
1964 ToolResult {
1965 call_id: "c".to_owned(),
1966 name: "t".to_owned(),
1967 ok,
1968 content: content.to_owned(),
1969 error: error.map(str::to_owned),
1970 metadata: serde_json::Map::new(),
1971 }
1972 }
1973
1974 #[test]
1975 fn observations_keep_both_error_and_output() {
1976 assert_eq!(observation(&result(true, "data", None)), "data");
1977 assert_eq!(
1978 observation(&result(false, " out ", Some(" bad "))),
1979 "bad\nout"
1980 );
1981 assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
1982 assert_eq!(observation(&result(false, "", None)), "error");
1983 }
1984
1985 #[test]
1986 fn summaries_show_the_first_line() {
1987 assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
1988 assert_eq!(summarize(&result(true, " ", None)), "(no output)");
1989 assert_eq!(
1990 summarize(&result(false, "", Some("No such file: x\nmore"))),
1991 "error: No such file: x"
1992 );
1993 assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
1994 assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
1995 }
1996
1997 #[test]
1998 fn previews_use_python_json_and_cut_at_160_characters() {
1999 let Value::Object(short) = json!({"path": "src/main.rs"}) else {
2000 unreachable!()
2001 };
2002 assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
2003
2004 let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
2005 unreachable!()
2006 };
2007 let preview = preview_arguments(&long);
2008 assert!(preview.ends_with(" ..."));
2009 assert_eq!(preview.chars().count(), 164);
2010 }
2011
2012 #[test]
2013 fn invalid_json_is_reported_with_a_python_repr_preview() {
2014 let call = ToolCall {
2015 id: "c1".to_owned(),
2016 name: "read_file".to_owned(),
2017 arguments: serde_json::Map::new(),
2018 };
2019 let result = invalid_arguments_result(&call, "{\"path\": ");
2020 let error = result.error.as_deref().unwrap();
2021 assert_eq!(
2023 error.lines().next(),
2024 Some(
2025 "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
2026 Call the tool again with its arguments as a single valid JSON object."
2027 )
2028 );
2029 assert_eq!(
2030 error.lines().nth(1),
2031 Some(
2032 "The JSON ends at character 9 inside the top-level object, before it is \
2033 complete: EOF while parsing a value."
2034 )
2035 );
2036 assert!(!result.ok);
2037 assert_eq!(result.call_id, "c1");
2038 }
2039}