1use crate::approval::ApprovalGate;
25use crate::config::EgressMode;
26use crate::config::{AgentsConfig, CompactionMode, LimitsConfig};
27use crate::guardrails::Guardrails;
28use crate::limits::LimitKind;
29use crate::memory::sizing::{
30 aged_view, calibrated_budget, result_cap, shorten_middle, sized_reserve,
31};
32use crate::memory::working::{
33 apply_progress, apply_summary, compacted_notice, compaction_failed_notice, compaction_plan,
34 count_spec_tokens, count_tokens, fit_pinned, fits, python_strip, summary_request_text,
35 trimmed_notice, Cut, Fitted, KEEP_RECENT, SUMMARY_MAX_TOKENS, SUMMARY_RETRY_NOTE,
36 SUMMARY_SYSTEM_PROMPT,
37};
38use crate::observability::Recorder;
39use crate::prompt::time_note;
40use crate::provider::reasoning::REASONING_LOOP;
41use crate::provider::{Provider, ProviderError};
42use crate::pyjson::{python_float_repr, python_json_dumps};
43use crate::router::Router;
44use crate::session::AgentState;
45use crate::tools::{ToolContext, ToolRegistry};
46use crate::turn::TurnSummary;
47use crate::types::{
48 python_repr, AgentPhase, CompletionRequest, Message, Role, Step, ToolCall, ToolResult,
49 ToolSpec, Usage,
50};
51use crate::vault::StreamRedactor;
52use futures_util::StreamExt;
53use serde_json::{json, Value};
54use std::collections::HashMap;
55use std::sync::atomic::{AtomicBool, Ordering};
56use std::sync::Arc;
57use std::time::{Duration, Instant};
58use thiserror::Error;
59
60pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
62
63pub const MAX_CONTINUATIONS: u64 = 3;
65
66const SUMMARY_MARGIN_TOKENS: u64 = 256;
69
70const MIN_TRANSCRIPT_TOKENS: u64 = 1_024;
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum SummaryError {
76 Cancelled,
77 Failed(String),
79 Empty,
81}
82
83#[derive(Debug, Clone)]
85pub(crate) struct WrittenSummary {
86 pub outcome: Result<String, SummaryError>,
87 pub usage: Usage,
88 pub model: String,
89}
90
91struct Compaction {
93 notice: String,
94 summary: Option<String>,
95}
96
97struct TurnWindow<'g> {
100 goal_text: &'g str,
102 goal: usize,
104 continuation: Option<usize>,
106 retry_at: Option<u64>,
108 trim_announced: bool,
110 trimmed: usize,
112 aged: usize,
114}
115
116pub fn continuation_notice(index: u64) -> String {
118 format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
119}
120
121pub const ANSWER_PROMPT: &str =
123 "Your last reply was empty. Give the user your answer now, as plain text.";
124
125pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
127
128pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
130
131pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
133
134pub const REASONING_LOOP_NOTICE: &str =
137 "\n[the model's reasoning was repeating itself; stopped it]\n";
138
139pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
141
142#[derive(Clone, Default)]
147pub struct CancelToken {
148 inner: Arc<CancelInner>,
149}
150
151impl std::fmt::Debug for CancelToken {
152 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 formatter
154 .debug_struct("CancelToken")
155 .field("cancelled", &self.is_cancelled())
156 .finish()
157 }
158}
159
160#[derive(Default)]
161struct CancelInner {
162 flag: AtomicBool,
163 notify: tokio::sync::Notify,
164}
165
166impl CancelToken {
167 pub fn cancel(&self) {
168 self.inner.flag.store(true, Ordering::SeqCst);
169 self.inner.notify.notify_waiters();
170 }
171
172 pub fn is_cancelled(&self) -> bool {
173 self.inner.flag.load(Ordering::SeqCst)
174 }
175
176 pub fn clear(&self) {
177 self.inner.flag.store(false, Ordering::SeqCst);
178 }
179
180 pub async fn cancelled(&self) {
182 loop {
183 let notified = self.inner.notify.notified();
184 tokio::pin!(notified);
185 notified.as_mut().enable();
187 if self.is_cancelled() {
188 return;
189 }
190 notified.await;
191 }
192 }
193}
194
195#[derive(Debug, Clone, Copy)]
202#[non_exhaustive]
203pub enum TurnEvent<'a> {
204 Text(&'a str),
206 Notice(&'a str),
210 Thinking(&'a str),
213 ToolCall { call: &'a ToolCall, text: &'a str },
215 ToolResult {
218 call: &'a ToolCall,
219 result: &'a ToolResult,
220 observation: &'a str,
221 text: &'a str,
222 },
223 Usage {
227 step: &'a crate::types::Usage,
228 session: &'a crate::types::Usage,
229 },
230 Compacted {
235 notice: &'a str,
236 summary: Option<&'a str>,
237 },
238 #[cfg(feature = "agent86ui")]
242 Ui(&'a agent86_ui::AgentMessage),
243}
244
245impl<'a> TurnEvent<'a> {
246 pub fn text(&self) -> &'a str {
248 match *self {
249 Self::Text(text)
250 | Self::Notice(text)
251 | Self::ToolCall { text, .. }
252 | Self::ToolResult { text, .. }
253 | Self::Compacted { notice: text, .. } => text,
254 Self::Thinking(_) | Self::Usage { .. } => "",
255 #[cfg(feature = "agent86ui")]
256 Self::Ui(_) => "",
257 }
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Error)]
263pub enum HarnessError {
264 #[error(transparent)]
265 Provider(#[from] ProviderError),
266
267 #[error("Circuit tripped: {0}")]
268 CircuitTripped(String),
269
270 #[error(
271 "The '{provider}' provider ended its stream for model {} without a final completion. \
272 The response was truncated; retry, or check the endpoint's streaming implementation.",
273 python_repr(model)
274 )]
275 NoFinalCompletion { provider: String, model: String },
276}
277
278impl HarnessError {
279 pub fn python_type(&self) -> &'static str {
282 match self {
283 Self::Provider(_) => "ProviderError",
284 Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
285 }
286 }
287}
288
289pub struct CircuitBreaker {
291 limits: LimitsConfig,
292 steps: u32,
293 cost_usd: f64,
294 consecutive_errors: u32,
295 started: Instant,
296}
297
298impl CircuitBreaker {
299 pub fn new(limits: &LimitsConfig) -> Self {
300 Self {
301 limits: limits.clone(),
302 steps: 0,
303 cost_usd: 0.0,
304 consecutive_errors: 0,
305 started: Instant::now(),
306 }
307 }
308
309 pub fn steps(&self) -> u32 {
310 self.steps
311 }
312
313 pub fn max_steps(&self) -> u32 {
315 self.limits.max_steps
316 }
317
318 pub fn set_max_steps(&mut self, max_steps: u32) {
320 self.limits.max_steps = max_steps;
321 }
322
323 pub fn out_of_steps(&self) -> bool {
325 self.steps >= self.limits.max_steps
326 }
327
328 pub fn before_step(&self) -> Result<(), HarnessError> {
330 let limits = &self.limits;
331 if self.steps >= limits.max_steps {
332 return Err(trip(format!(
333 "step budget reached ({} steps)",
334 limits.max_steps
335 )));
336 }
337 if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
338 return Err(trip(format!(
339 "cost cap reached (${:.4} >= ${})",
340 self.cost_usd,
341 python_float_repr(limits.max_cost_usd)
342 )));
343 }
344 let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
345 if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
346 return Err(trip(format!(
347 "wall-clock limit reached ({}s)",
348 limits.max_wall_clock_s
349 )));
350 }
351 Ok(())
352 }
353
354 pub fn record_step(&mut self, usage: &Usage) {
355 self.steps += 1;
356 self.cost_usd += usage.cost_usd;
357 }
358
359 pub fn cost(&self) -> f64 {
362 self.cost_usd
363 }
364
365 pub fn record_cost(&mut self, cost_usd: f64) {
366 self.cost_usd += cost_usd;
367 }
368
369 pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
370 if ok {
371 self.consecutive_errors = 0;
372 return Ok(());
373 }
374 self.consecutive_errors += 1;
375 if self.consecutive_errors > self.limits.max_consecutive_errors {
376 return Err(trip(format!(
377 "aborted after {} consecutive tool errors",
378 self.consecutive_errors
379 )));
380 }
381 Ok(())
382 }
383}
384
385fn trip(reason: String) -> HarnessError {
386 HarnessError::CircuitTripped(reason)
387}
388
389pub struct Harness {
391 pub provider: Arc<dyn Provider>,
394 pub router: Router,
396 pub tracer: crate::otel::Tracer,
398 pub registry: ToolRegistry,
399 pub context: ToolContext,
400 pub limits: LimitsConfig,
401 pub agents: AgentsConfig,
403 pub system: Message,
404 pub max_tokens: u32,
407 pub session_limits: crate::limits::SessionLimits,
410 pub context_window: u64,
413 pub gate: ApprovalGate,
415 pub guardrails: Guardrails,
417 pub recorder: Recorder,
419 pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
422 pub memory: Option<crate::session::SessionStore>,
425 pub cancel: CancelToken,
427 pub subagents: crate::subagent::SubagentState,
430 pub calibration: crate::memory::sizing::Calibration,
433 pub verify: crate::verify::Verify,
435}
436
437impl Harness {
438 pub(crate) fn system_message(&self, extra: Option<&str>) -> Message {
443 let offered = self.delegation_offered(&self.context, 0);
444 if let Some((persona, preloaded, _)) = self.subagents.main() {
446 return self.filtered_system(&persona, &self.context, &preloaded, offered, extra);
447 }
448 self.system_for(&self.context, offered, extra)
449 }
450
451 pub(crate) fn system_for(
455 &self,
456 ctx: &ToolContext,
457 delegation_offered: bool,
458 extra: Option<&str>,
459 ) -> Message {
460 let mut system = self.system.clone();
461 if let Some(section) = self
462 .mcp
463 .as_ref()
464 .map(|mcp| mcp.prompt_section())
465 .filter(|section| !section.is_empty())
466 {
467 system.content = format!("{}\n\n{section}", system.content);
468 }
469 if delegation_offered {
470 if let Some(section) = self.specialty_listing(ctx) {
471 system.content = format!("{}\n\n{section}", system.content);
472 }
473 }
474 if let Some(section) = ctx.secrets.prompt_section() {
475 system.content = format!("{}\n\n{section}", system.content);
476 }
477 if crate::ask::reachable(ctx) && ctx.allowed_tool(crate::ask::ASK_USER) {
480 #[cfg(feature = "agent86ui")]
481 let drawing = ctx.ui.is_some() && ctx.allowed_tool(crate::agent86ui::RENDER_UI);
482 #[cfg(not(feature = "agent86ui"))]
483 let drawing = false;
484 system.content = format!(
485 "{}\n\n{}",
486 system.content,
487 crate::ask::prompt_section(drawing)
488 );
489 }
490 #[cfg(feature = "agent86ui")]
493 if let Some(ui) = ctx.ui.as_deref() {
494 if ctx.allowed_tool(crate::agent86ui::RENDER_UI) {
495 system.content = format!("{}\n\n{}", system.content, ui.prompt_section());
496 }
497 }
498 if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
499 system.content = format!("{}\n\n{extra}", system.content);
500 }
501 system
502 }
503
504 pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
512 self.context_budget_with(
513 system,
514 specs,
515 self.active_context_window(),
516 self.output_cap(),
517 self.active_provider().model(),
518 )
519 }
520
521 pub(crate) fn cap_result(&self, content: String, budget: u64) -> String {
524 if !self.limits.context_sizing {
525 return content;
526 }
527 shorten_middle(
528 &content,
529 result_cap(budget, self.context.policy.max_output_chars),
530 )
531 }
532
533 pub(crate) fn request_view(
536 &self,
537 messages: &[Message],
538 budget: u64,
539 ) -> crate::memory::sizing::Aged {
540 if self.limits.context_sizing {
541 aged_view(messages, budget)
542 } else {
543 crate::memory::sizing::Aged {
544 messages: messages.to_vec(),
545 aged: 0,
546 }
547 }
548 }
549
550 pub(crate) fn context_budget_with(
556 &self,
557 system: &Message,
558 specs: &[ToolSpec],
559 window: u64,
560 output_cap: u32,
561 model: &str,
562 ) -> u64 {
563 let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
564 let (ratio, reserve) = if self.limits.context_sizing {
565 (
566 self.calibration.ratio(model),
567 sized_reserve(self.limits.context_reserve_tokens, window),
568 )
569 } else {
570 (1.0, self.limits.context_reserve_tokens)
571 };
572 calibrated_budget(
573 window,
574 overhead,
575 reserve,
576 u64::from(output_cap),
577 self.limits.max_context_tokens,
578 ratio,
579 )
580 }
581
582 fn request_tools(&self) -> Vec<ToolSpec> {
585 let mut tools = self.registry.specs();
586 tools.retain(|spec| self.context.scope_allows(&spec.name));
587 tools
588 }
589
590 pub(crate) async fn write_summary(&self, messages: &[Message]) -> WrittenSummary {
598 let (summarizer, window) = self.summary_model();
599 let model = summarizer.model().to_owned();
600 let first_cap = SUMMARY_MAX_TOKENS * 2;
601 let share = |divisor: u64| u32::try_from(window / divisor).unwrap_or(u32::MAX);
605 let retry_cap = (SUMMARY_MAX_TOKENS * 8)
606 .min(share(4))
607 .max(first_cap.min(share(2)));
608 let instructions = message(Role::System, SUMMARY_SYSTEM_PROMPT);
609 let overhead = count_tokens(std::slice::from_ref(&instructions))
610 + count_tokens(&[message(Role::User, SUMMARY_RETRY_NOTE)])
611 + SUMMARY_MARGIN_TOKENS;
612 let room = window
613 .saturating_sub(overhead + u64::from(retry_cap))
614 .max(MIN_TRANSCRIPT_TOKENS);
615 let transcript =
616 summary_request_text(messages, usize::try_from(room * 4).unwrap_or(usize::MAX));
617 let mut usage = Usage::default();
618 let mut attempt = 0;
619 loop {
620 let (text, cap) = if attempt == 0 {
621 (transcript.clone(), first_cap)
622 } else {
623 (format!("{transcript}\n\n{SUMMARY_RETRY_NOTE}"), retry_cap)
624 };
625 let request = CompletionRequest {
626 model: model.clone(),
627 messages: vec![instructions.clone(), message(Role::User, &text)],
628 tools: Vec::new(),
629 temperature: 0.0,
630 max_tokens: Some(cap),
632 stream: false,
633 };
634 let completion = tokio::select! {
635 biased;
636 () = self.cancel.cancelled() => {
638 return WrittenSummary { outcome: Err(SummaryError::Cancelled), usage, model };
639 }
640 completion = summarizer.complete(request) => completion,
641 };
642 let completion = match completion {
643 Ok(completion) => completion,
644 Err(error) => {
645 return WrittenSummary {
646 outcome: Err(SummaryError::Failed(format!("ProviderError: {error}"))),
647 usage,
648 model,
649 }
650 }
651 };
652 usage = usage + completion.usage;
653 let text = python_strip(&completion.text).to_owned();
654 if !text.is_empty() {
655 return WrittenSummary {
656 outcome: Ok(text),
657 usage,
658 model,
659 };
660 }
661 if attempt > 0 {
662 return WrittenSummary {
663 outcome: Err(SummaryError::Empty),
664 usage,
665 model,
666 };
667 }
668 attempt += 1;
669 }
670 }
671
672 async fn compact_if_needed(
687 &self,
688 state: &mut AgentState,
689 extra_system: Option<&str>,
690 summary: &mut TurnSummary,
691 breaker: &mut CircuitBreaker,
692 window: &mut TurnWindow<'_>,
693 ) -> Option<Compaction> {
694 if self.limits.compaction != CompactionMode::Summarize {
695 return None;
696 }
697 let system = self.system_message(extra_system);
698 let budget = self.context_budget(&system, &self.request_tools());
699 if fits(&self.request_view(&state.messages, budget).messages, budget) {
702 return None;
703 }
704 let tokens = count_tokens(&state.messages);
705 if window.retry_at.is_some_and(|at| tokens < at) {
706 return None;
707 }
708 let cut = compaction_plan(
712 &state.messages,
713 budget,
714 KEEP_RECENT,
715 window.goal,
716 window.continuation,
717 )?;
718 let sid = state.session_id.clone();
719 let end = cut.cut();
720 let replaced = cut.replaced();
721 let prefix = &state.messages[..end];
722 let dropped_tokens = count_tokens(prefix);
723 let written = self.write_summary(prefix).await;
724 summary.add_usage(&written.usage);
725 breaker.record_cost(written.usage.cost_usd);
726 let failed = |window: &mut TurnWindow<'_>, status: &str, error: Option<String>| {
727 window.retry_at = Some(tokens + (budget / 4).max(1));
728 let mut fields = vec![
729 ("status", json!(status)),
730 ("fallback", json!("drop")),
731 ("dropped", json!(replaced)),
732 ];
733 if let Some(error) = error {
734 fields.push(("error", json!(error)));
735 }
736 self.recorder.event(&sid, "compaction", fields);
737 Some(Compaction {
738 notice: compaction_failed_notice(replaced),
739 summary: None,
740 })
741 };
742 let text = match written.outcome {
743 Ok(text) => text,
744 Err(SummaryError::Cancelled) => return None,
745 Err(SummaryError::Failed(error)) => return failed(window, "failed", Some(error)),
746 Err(SummaryError::Empty) => return failed(window, "empty", None),
747 };
748 window.retry_at = None;
749
750 if let Some(memory) = &self.memory {
752 let _ = memory.record_compaction(&sid, &text, prefix);
753 }
754 let before = state.messages.len();
755 let kept = state.messages.split_off(end);
756 state.messages = match cut {
757 Cut::Earlier(_) => apply_summary(&text, kept),
758 Cut::WithinTurn { .. } => apply_progress(window.goal_text, &text, kept),
759 };
760 let removed = before - state.messages.len();
761 window.goal = match cut {
764 Cut::Earlier(_) => window.goal - removed,
765 Cut::WithinTurn { .. } => 0,
766 };
767 if let Some(start) = window.continuation.as_mut() {
768 *start -= removed;
769 }
770 summary.compactions += 1;
771 let mut fields = vec![
772 ("status", json!("ok")),
773 ("dropped", json!(replaced)),
774 ("dropped_tokens", json!(dropped_tokens)),
775 (
776 "summary_tokens",
777 json!(count_tokens(&[message(Role::User, &text)])),
778 ),
779 ("kept", json!(state.messages.len())),
780 ("model", json!(written.model)),
781 ];
782 if matches!(cut, Cut::WithinTurn { .. }) {
783 fields.push(("scope", json!("turn")));
784 }
785 self.recorder.event(&sid, "compaction", fields);
786 if let Some(memory) = &self.memory {
789 let _ = memory.persist(state);
790 }
791 Some(Compaction {
792 notice: compacted_notice(replaced),
793 summary: Some(text),
794 })
795 }
796
797 pub async fn run_turn(
804 &self,
805 state: &mut AgentState,
806 goal: &str,
807 on_text: impl FnMut(&str),
808 ) -> Result<String, HarnessError> {
809 self.run_turn_as(state, goal, goal, on_text).await
810 }
811
812 pub async fn run_turn_as(
816 &self,
817 state: &mut AgentState,
818 user_text: &str,
819 display_text: &str,
820 mut on_text: impl FnMut(&str),
821 ) -> Result<String, HarnessError> {
822 self.run_turn_events(state, user_text, display_text, |event| {
823 on_text(event.text())
824 })
825 .await
826 }
827
828 pub async fn run_turn_events(
832 &self,
833 state: &mut AgentState,
834 user_text: &str,
835 display_text: &str,
836 on_event: impl FnMut(TurnEvent<'_>),
837 ) -> Result<String, HarnessError> {
838 self.run_turn_with(state, user_text, display_text, None, on_event)
839 .await
840 }
841
842 pub async fn run_skill_turn(
849 &self,
850 state: &mut AgentState,
851 skill: &Arc<crate::skills::Skill>,
852 task: &str,
853 display_text: &str,
854 on_event: impl FnMut(TurnEvent<'_>),
855 ) -> Result<String, HarnessError> {
856 let user_text = crate::skills::skill_request(skill, task);
857 self.run_turn_with(state, &user_text, display_text, Some(skill), on_event)
858 .await
859 }
860
861 async fn run_turn_with(
862 &self,
863 state: &mut AgentState,
864 user_text: &str,
865 display_text: &str,
866 skill: Option<&Arc<crate::skills::Skill>>,
867 on_event: impl FnMut(TurnEvent<'_>),
868 ) -> Result<String, HarnessError> {
869 self.cancel.clear();
871 self.context.clear_skill();
876 if let Some(skill) = skill {
877 self.context.activate_skill(skill);
878 }
879 let started = Instant::now();
880 let mut span = self.tracer.start(
882 "turn",
883 vec![
884 ("session.id", json!(state.session_id)),
885 (
886 "gen_ai.request.model",
887 json!(self.active_provider().model()),
888 ),
889 ],
890 );
891 let mut summary = TurnSummary::default();
892 let secrets = &self.context.secrets;
895 let (user_text, display_text) = (secrets.redact(user_text), secrets.redact(display_text));
896 let result = self
897 .turn(state, &user_text, &display_text, &mut summary, on_event)
898 .await;
899 self.context.clear_skill();
900 summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
901 state.last_turn = Some(summary);
902 if let Err(error) = &result {
903 state.phase = AgentPhase::Error;
904 let reason = match error {
905 HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
906 HarnessError::Provider(detail) => {
907 format!("provider stream failed: ProviderError: {detail}")
908 }
909 HarnessError::NoFinalCompletion { .. } => {
910 "provider stream ended without a final completion".to_owned()
911 }
912 };
913 self.recorder.event(
914 &state.session_id,
915 "turn_end",
916 vec![("status", json!("error")), ("reason", json!(reason))],
917 );
918 }
919 span.set(turn_attributes(state, self.active_provider().model()));
922 if let Err(error) = &result {
923 span.fail(error.python_type(), &error.to_string());
924 }
925 self.tracer.end(span);
926 result
927 }
928
929 async fn turn(
930 &self,
931 state: &mut AgentState,
932 goal: &str,
933 display_text: &str,
934 summary: &mut TurnSummary,
935 mut on_event: impl FnMut(TurnEvent<'_>),
936 ) -> Result<String, HarnessError> {
937 let mut output = String::new();
938 let mut emit = |event: TurnEvent<'_>| {
939 output.push_str(event.text());
940 on_event(event);
941 };
942
943 let sid = state.session_id.clone();
944 self.recorder
945 .event(&sid, "turn_start", vec![("task", json!(display_text))]);
946 self.verify.set_last(None);
947
948 let report = self.guardrails.inspect_ingress(goal);
950 if report.flagged() {
951 self.recorder.event(
952 &sid,
953 "guardrail",
954 vec![
955 ("stage", json!("ingress_input")),
956 ("findings", json!(report.summary())),
957 ],
958 );
959 if self.guardrails.should_block(&report) {
960 let refusal = format!(
961 "Refused: input tripped the ingress guardrail ({}).",
962 report.summary()
963 );
964 state.messages.push(message(Role::User, goal));
965 state.messages.push(message(Role::Assistant, &refusal));
966 state.phase = AgentPhase::Error;
967 self.recorder
968 .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
969 emit(TurnEvent::Text(&refusal));
970 return Ok(output);
971 }
972 emit(TurnEvent::Notice(&format!(
973 "[guardrail] input flagged: {}\n",
974 report.summary()
975 )));
976 }
977
978 let buffering = self.guardrails.egress == EgressMode::Redact;
981
982 self.route(goal, &sid)?;
984 let provider = self.active_provider();
985
986 let recall_note = self
988 .memory
989 .as_ref()
990 .and_then(|memory| memory.recall_note(goal));
991 let time = time_note(&jiff::ZonedDateTime::now());
993 let recall_note = Some(match recall_note {
994 Some(recalled) => format!("{time}\n\n{recalled}"),
995 None => time,
996 });
997 let mut window = TurnWindow {
1001 goal_text: goal,
1002 goal: state.messages.len(),
1003 continuation: None,
1004 retry_at: None,
1005 trim_announced: false,
1006 trimmed: 0,
1007 aged: 0,
1008 };
1009 state.messages.push(message(Role::User, goal));
1010 let mut limits = self.limits.clone();
1011 limits.max_steps = self.max_steps();
1012 let mut breaker = CircuitBreaker::new(&limits);
1013 let mut broken_streak = BrokenStreak::default();
1014 let mut continuation_start: Option<usize> = None;
1016 let mut continuation_parts: Vec<String> = Vec::new();
1017 let mut nudged = false;
1021 let mut ask_again = false;
1022 let mut unanswered_thinking = String::new();
1023 let mut verify_run = crate::verify::VerifyRun::default();
1025 let mut stall = crate::stall::StallWatch::new(self.limits.stall_nudge);
1027
1028 loop {
1029 if self.cancel.is_cancelled() {
1032 self.cancelled(state, breaker.steps(), &mut emit);
1033 return Ok(output);
1034 }
1035 if breaker.out_of_steps() {
1037 match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
1038 Some(raised) => breaker.set_max_steps(raised),
1039 None if self.cancel.is_cancelled() => {
1041 self.cancelled(state, breaker.steps(), &mut emit);
1042 return Ok(output);
1043 }
1044 None => {}
1045 }
1046 }
1047 breaker.before_step()?;
1048
1049 window.continuation = continuation_start;
1052 if let Some(compaction) = self
1053 .compact_if_needed(
1054 state,
1055 recall_note.as_deref(),
1056 summary,
1057 &mut breaker,
1058 &mut window,
1059 )
1060 .await
1061 {
1062 continuation_start = window.continuation;
1063 window.trim_announced = compaction.summary.is_none();
1066 emit(TurnEvent::Compacted {
1069 notice: &compaction.notice,
1070 summary: compaction.summary.as_deref(),
1071 });
1072 }
1073
1074 let estimated;
1077 let step_budget;
1078 let mut completion = {
1079 let system = self.system_message(recall_note.as_deref());
1080 let tools = self.request_tools();
1082 let budget = self.context_budget(&system, &tools);
1083 step_budget = budget;
1084 let aged = self.request_view(&state.messages, budget);
1086 self.announce_age(&sid, aged.aged, budget, &mut window);
1087 let fitted = fit_pinned(&aged.messages, budget, Some(window.goal));
1088 self.announce_trim(&sid, &fitted, budget, &mut window, &mut emit);
1089 let mut request_messages = Vec::with_capacity(fitted.messages.len() + 1);
1090 request_messages.push(system);
1091 request_messages.extend(fitted.messages);
1092 if std::mem::take(&mut ask_again) {
1093 request_messages.push(message(Role::User, ANSWER_PROMPT));
1094 }
1095 estimated = count_tokens(&request_messages) + count_spec_tokens(&tools);
1096 let request = CompletionRequest {
1097 model: provider.model().to_owned(),
1098 messages: request_messages,
1099 tools,
1100 temperature: request_temperature(
1102 provider.as_ref(),
1103 self.subagents.main().and_then(|main| main.2),
1104 ),
1105 max_tokens: Some(self.output_cap()),
1106 stream: true,
1107 };
1108 let mut span = self.tracer.start(
1110 "model_call",
1111 vec![
1112 ("gen_ai.system", json!(provider.name())),
1113 ("gen_ai.request.model", json!(provider.model())),
1114 ("agent86.step", json!(breaker.steps() + 1)),
1115 ],
1116 );
1117 let mut stream = provider.stream(request);
1118 let mut completion = None;
1119 let mut buffered = String::new();
1120 let mut redactor = StreamRedactor::default();
1123 let mut thinking_redactor = StreamRedactor::default();
1124 loop {
1125 let next = tokio::select! {
1128 biased;
1129 () = self.cancel.cancelled() => None,
1130 delta = stream.next() => Some(delta),
1131 };
1132 let Some(Some(delta)) = next else { break };
1133 let delta = match delta {
1134 Ok(delta) => delta,
1135 Err(error) => {
1136 span.set(model_call_attributes(None));
1137 span.fail("ProviderError", &error.to_string());
1138 self.tracer.end(span);
1139 return Err(error.into());
1140 }
1141 };
1142 if !delta.thinking.is_empty() && !buffering {
1145 let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
1146 if !shown.is_empty() {
1147 emit(TurnEvent::Thinking(&shown));
1148 }
1149 }
1150 if !delta.text.is_empty() {
1151 if buffering {
1152 buffered.push_str(&delta.text);
1153 } else {
1154 let shown = redactor.push(&self.context.secrets, &delta.text);
1155 if !shown.is_empty() {
1156 emit(TurnEvent::Text(&shown));
1157 }
1158 }
1159 }
1160 if delta.done && delta.completion.is_some() {
1161 completion = delta.completion;
1162 }
1163 }
1164 drop(stream);
1165 let held = thinking_redactor.finish(&self.context.secrets);
1166 if !held.is_empty() {
1167 emit(TurnEvent::Thinking(&held));
1168 }
1169 let held = redactor.finish(&self.context.secrets);
1170 if !held.is_empty() {
1171 emit(TurnEvent::Text(&held));
1172 }
1173 span.set(model_call_attributes(completion.as_ref()));
1174 self.tracer.end(span);
1175 if self.cancel.is_cancelled() {
1176 let partial = self
1178 .guardrails
1179 .inspect_egress(&self.context.secrets.redact(&buffered))
1180 .1;
1181 if !partial.is_empty() {
1182 emit(TurnEvent::Text(&partial));
1183 }
1184 self.cancelled(state, breaker.steps(), &mut emit);
1185 return Ok(output);
1186 }
1187 completion.ok_or_else(|| HarnessError::NoFinalCompletion {
1188 provider: provider.name().to_owned(),
1189 model: provider.model().to_owned(),
1190 })?
1191 };
1192
1193 breaker.record_step(&completion.usage);
1194 if self.limits.context_sizing {
1195 self.calibration.observe(
1196 provider.model(),
1197 estimated,
1198 completion.usage.input_tokens,
1199 );
1200 }
1201 summary.steps = u64::from(breaker.steps());
1202 summary.add_usage(&completion.usage);
1203 emit(TurnEvent::Usage {
1206 step: &completion.usage,
1207 session: &(state.usage + completion.usage),
1208 });
1209 let names: Vec<&str> = completion
1210 .tool_calls
1211 .iter()
1212 .map(|call| call.name.as_str())
1213 .collect();
1214 self.recorder.event(
1215 &sid,
1216 "model_call",
1217 vec![
1218 ("step", json!(breaker.steps())),
1219 ("model", json!(provider.model())),
1220 ("input_tokens", json!(completion.usage.input_tokens)),
1221 ("output_tokens", json!(completion.usage.output_tokens)),
1222 ("cost_usd", json!(completion.usage.cost_usd)),
1223 ("stop_reason", json!(completion.stop_reason)),
1224 ("tool_calls", json!(names)),
1225 ],
1226 );
1227
1228 if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
1229 emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
1230 }
1231 let stopped = completion
1235 .stop_reason
1236 .as_deref()
1237 .and_then(|reason| reason.strip_prefix(crate::provider::STOPPED_PREFIX))
1238 .map(str::to_owned);
1239 if let Some(reason) = &stopped {
1240 emit(TurnEvent::Notice(&format!(
1241 "\n[{} stopped the reply: {reason}]\n",
1242 provider.name()
1243 )));
1244 }
1245
1246 let mut from_thinking = false;
1252 if completion.tool_calls.is_empty()
1253 && completion.stop_reason.as_deref() != Some("max_tokens")
1254 && stopped.is_none()
1255 && completion.text.trim().is_empty()
1256 && continuation_start.is_none()
1257 {
1258 if !completion.thinking.trim().is_empty() {
1259 unanswered_thinking = std::mem::take(&mut completion.thinking);
1260 }
1261 if !nudged && !breaker.out_of_steps() {
1262 nudged = true;
1263 ask_again = true;
1264 self.recorder.event(
1265 &sid,
1266 "empty_answer",
1267 vec![
1268 ("step", json!(breaker.steps())),
1269 ("model", json!(provider.model())),
1270 ("thinking_chars", json!(unanswered_thinking.chars().count())),
1271 ],
1272 );
1273 record_step(
1274 state,
1275 Step {
1276 index: state.steps.len() as u64 + 1,
1277 phase: AgentPhase::Execute,
1278 thought: String::new(),
1279 tool_calls: Vec::new(),
1280 results: Vec::new(),
1281 usage: completion.usage,
1282 },
1283 );
1284 self.checkpoint(state);
1285 emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1286 continue;
1287 }
1288 if unanswered_thinking.trim().is_empty() {
1289 emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1290 if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1293 emit(TurnEvent::Notice(&format!(
1294 "{}\n",
1295 crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1296 )));
1297 }
1298 } else {
1299 completion.text = std::mem::take(&mut unanswered_thinking);
1300 from_thinking = true;
1301 emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1302 }
1303 }
1304
1305 let answer = self.context.secrets.redact(&completion.text);
1308 let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1309 let text = if buffering {
1310 if !redacted.is_empty() {
1311 emit(TurnEvent::Text(&redacted));
1312 }
1313 redacted
1314 } else {
1315 if from_thinking {
1317 emit(TurnEvent::Text(&answer));
1318 }
1319 answer
1320 };
1321 if egress.flagged() {
1322 self.recorder.event(
1323 &sid,
1324 "guardrail",
1325 vec![
1326 ("stage", json!("egress")),
1327 ("findings", json!(egress.summary())),
1328 ],
1329 );
1330 emit(TurnEvent::Notice(&format!(
1331 "\n[guardrail] output flagged: {}\n",
1332 egress.summary()
1333 )));
1334 }
1335 let mut tool_calls = completion.tool_calls;
1336 let repairs = self.repair_broken_calls(&mut tool_calls, &sid);
1338 self.scan_tool_arguments(&tool_calls, &sid);
1339 let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1340 if cut_off
1345 && tool_calls.is_empty()
1346 && text.trim().is_empty()
1347 && continuation_start.is_none()
1348 {
1349 let cap = self.output_cap();
1350 if self
1351 .raise_limit(LimitKind::Output, None, &sid, cap, false)
1352 .is_some()
1353 {
1354 record_step(
1355 state,
1356 Step {
1357 index: state.steps.len() as u64 + 1,
1358 phase: AgentPhase::Execute,
1359 thought: String::new(),
1360 tool_calls: Vec::new(),
1361 results: Vec::new(),
1362 usage: completion.usage,
1363 },
1364 );
1365 self.checkpoint(state);
1366 continue;
1367 }
1368 }
1369 let mut step = Step {
1370 index: state.steps.len() as u64 + 1,
1371 phase: AgentPhase::Execute,
1372 thought: text.clone(),
1373 tool_calls: tool_calls.clone(),
1374 results: Vec::new(),
1375 usage: completion.usage,
1376 };
1377 state.messages.push(Message {
1378 tool_calls: tool_calls.clone(),
1379 ..message(Role::Assistant, &text)
1380 });
1381
1382 if tool_calls.is_empty() {
1383 if cut_off && summary.continuations < MAX_CONTINUATIONS {
1384 summary.continuations += 1;
1385 continuation_start.get_or_insert(state.messages.len() - 1);
1386 continuation_parts.push(text);
1387 state.messages.push(message(Role::User, CONTINUE_PROMPT));
1388 record_step(state, step);
1389 self.checkpoint(state);
1390 self.recorder.event(
1391 &sid,
1392 "continuation",
1393 vec![
1394 ("index", json!(summary.continuations)),
1395 ("step", json!(breaker.steps())),
1396 ("model", json!(provider.model())),
1397 (
1398 "chars",
1399 json!(continuation_parts
1400 .last()
1401 .map_or(0, |part| part.chars().count())),
1402 ),
1403 ],
1404 );
1405 emit(TurnEvent::Notice(&continuation_notice(
1406 summary.continuations,
1407 )));
1408 continue;
1409 }
1410 if let Some(start) = continuation_start.take() {
1411 continuation_parts.push(text);
1413 let joined = std::mem::take(&mut continuation_parts).concat();
1414 state.messages.truncate(start);
1415 state.messages.push(message(Role::Assistant, &joined));
1416 step.thought = joined;
1417 }
1418 let steps_left = !breaker.out_of_steps();
1421 if let crate::verify::Gate::SendBack(feedback) =
1422 self.verify_answer(&mut verify_run, steps_left, &sid, &mut emit)
1423 {
1424 record_step(state, step);
1425 state.messages.push(message(Role::User, &feedback));
1426 self.checkpoint(state);
1427 continue;
1428 }
1429 let outcome = step.thought.clone();
1430 record_step(state, step);
1431 state.phase = AgentPhase::Done;
1432 self.recorder.event(
1433 &sid,
1434 "turn_end",
1435 vec![
1436 ("status", json!("done")),
1437 ("steps", json!(breaker.steps())),
1438 ("continuations", json!(summary.continuations)),
1439 ],
1440 );
1441 if let Some(memory) = &self.memory {
1442 let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1444 }
1445 return Ok(output);
1446 }
1447
1448 continuation_start = None;
1450 continuation_parts.clear();
1451
1452 if self.cancel.is_cancelled() {
1456 for call in &tool_calls {
1457 let result = not_executed(call, "cancelled");
1458 state.messages.push(Message {
1459 tool_call_id: Some(call.id.clone()),
1460 name: Some(call.name.clone()),
1461 ..message(Role::Tool, &observation(&result))
1462 });
1463 step.results.push(result);
1464 }
1465 record_step(state, step);
1466 self.cancelled(state, breaker.steps(), &mut emit);
1467 return Ok(output);
1468 }
1469
1470 for call in &tool_calls {
1472 let text = format!(
1473 "\n[tool] {}({})\n",
1474 call.name,
1475 preview_arguments(&call.arguments)
1476 );
1477 emit(TurnEvent::ToolCall { call, text: &text });
1478 }
1479 let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1480 for notice in self.take_notices() {
1484 emit(TurnEvent::Notice(&format!("{notice}\n")));
1485 }
1486 let mut asked_in_text: Option<String> = None;
1488 for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1489 summary.tool_calls += 1;
1490 #[cfg(feature = "agent86ui")]
1493 let result = {
1494 let mut result = result;
1495 let (drawn, trace) = crate::agent86ui::take_drawn(&mut result.metadata);
1496 for message in &drawn {
1497 emit(TurnEvent::Ui(message));
1498 }
1499 if let Some(Value::Object(fields)) = trace {
1500 let fields: Vec<(&str, Value)> = fields
1503 .iter()
1504 .map(|(key, value)| (key.as_str(), value.clone()))
1505 .collect();
1506 self.recorder.event(&sid, "ui_render", fields);
1507 }
1508 match crate::agent86ui::take_wait(&mut result.metadata) {
1511 Some(surfaces) => self.ui_wait(call, result, surfaces, &sid),
1512 None => result,
1513 }
1514 };
1515 let mut result = self.ask_questions(call, result, &sid, &mut emit);
1518 if let Some(Value::String(text)) = result.metadata.remove(crate::ask::ASK_TEXT_KEY)
1519 {
1520 asked_in_text = Some(match asked_in_text.take() {
1521 Some(earlier) => format!("{earlier}\n\n{text}"),
1522 None => text,
1523 });
1524 }
1525 let result = self.annotate_broken_json(call, result, &repairs, &mut broken_streak);
1526 summary.add_usage(&delegated);
1529 step.usage = step.usage + delegated;
1530 breaker.record_cost(delegated.cost_usd);
1531 let (content, findings) = self.guardrails.observe(observation(&result));
1532 let content = self.cap_result(content, step_budget);
1534 if let Some(findings) = findings {
1535 self.recorder.event(
1536 &sid,
1537 "guardrail",
1538 vec![
1539 ("stage", json!("observation")),
1540 ("tool", json!(call.name)),
1541 ("findings", json!(findings)),
1542 ],
1543 );
1544 }
1545 emit(TurnEvent::ToolResult {
1546 call,
1547 result: &result,
1548 observation: &content,
1549 text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1550 });
1551 state.messages.push(Message {
1552 tool_call_id: Some(call.id.clone()),
1553 name: Some(call.name.clone()),
1554 ..message(Role::Tool, &content)
1555 });
1556 let ok = result.ok;
1557 verify_run.saw(&call.name, ok);
1558 stall.saw(call, &result, &content);
1559 step.results.push(result);
1560 if let Err(tripped) = breaker.record_tool_result(ok) {
1561 record_step(state, step);
1562 return Err(tripped);
1563 }
1564 }
1565 if let Some(questions) = asked_in_text {
1571 emit(TurnEvent::Text(&questions));
1572 state.messages.push(message(Role::Assistant, &questions));
1573 record_step(state, step);
1574 state.phase = AgentPhase::Done;
1575 self.recorder.event(
1576 &sid,
1577 "turn_end",
1578 vec![
1579 ("status", json!("done")),
1580 ("steps", json!(breaker.steps())),
1581 ("continuations", json!(summary.continuations)),
1582 ],
1583 );
1584 if let Some(memory) = &self.memory {
1585 let _ = memory.add_episode(&sid, goal, &questions, &Default::default());
1586 }
1587 return Ok(output);
1588 }
1589 if let Some(found) = stall.take() {
1592 self.remind_of_stall(&found, &sid, &mut emit);
1593 state.messages.push(message(Role::User, &found.note()));
1594 }
1595 record_step(state, step);
1596 self.checkpoint(state);
1597 if self.cancel.is_cancelled() {
1598 self.cancelled(state, breaker.steps(), &mut emit);
1599 return Ok(output);
1600 }
1601 }
1602 }
1603
1604 fn checkpoint(&self, state: &mut AgentState) {
1611 state.phase = AgentPhase::Execute;
1612 if let Some(memory) = &self.memory {
1613 let _ = memory.persist(state);
1614 }
1615 }
1616
1617 fn announce_trim(
1624 &self,
1625 sid: &str,
1626 fitted: &Fitted,
1627 budget: u64,
1628 window: &mut TurnWindow<'_>,
1629 emit: &mut impl FnMut(TurnEvent<'_>),
1630 ) {
1631 if fitted.dropped == window.trimmed {
1632 return;
1633 }
1634 window.trimmed = fitted.dropped;
1635 if fitted.dropped == 0 {
1636 return;
1637 }
1638 self.recorder.event(
1639 sid,
1640 "context_trim",
1641 vec![
1642 ("dropped", json!(fitted.dropped)),
1643 ("kept", json!(fitted.messages.len())),
1644 ("budget", json!(budget)),
1645 ("goal_pinned", json!(fitted.pinned)),
1646 ],
1647 );
1648 if !window.trim_announced {
1649 window.trim_announced = true;
1650 emit(TurnEvent::Notice(&trimmed_notice(fitted.dropped)));
1651 }
1652 }
1653
1654 fn remind_of_stall(
1658 &self,
1659 found: &crate::stall::Stall,
1660 sid: &str,
1661 emit: &mut impl FnMut(TurnEvent<'_>),
1662 ) {
1663 emit(TurnEvent::Notice(&found.notice()));
1664 let mut fields = vec![
1665 ("shape", json!(found.kind.as_str())),
1666 ("count", json!(found.count)),
1667 ];
1668 if let Some(tool) = &found.tool {
1669 fields.push(("tool", json!(tool)));
1670 }
1671 self.recorder.event(sid, "stall", fields);
1672 }
1673
1674 fn announce_age(&self, sid: &str, aged: usize, budget: u64, window: &mut TurnWindow<'_>) {
1678 if aged == window.aged {
1679 return;
1680 }
1681 window.aged = aged;
1682 self.recorder.event(
1683 sid,
1684 "context_age",
1685 vec![("aged", json!(aged)), ("budget", json!(budget))],
1686 );
1687 }
1688
1689 fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
1690 state.phase = AgentPhase::Error;
1691 self.recorder.event(
1692 &state.session_id,
1693 "turn_end",
1694 vec![
1695 ("status", json!("cancelled")),
1696 ("reason", json!("cancelled")),
1697 ("steps", json!(steps)),
1698 ],
1699 );
1700 emit(TurnEvent::Notice(CANCELLED_NOTICE));
1701 }
1702
1703 async fn execute_batch(
1717 &self,
1718 calls: &[ToolCall],
1719 sid: &str,
1720 spent: f64,
1721 ) -> Vec<(ToolResult, Usage)> {
1722 let eligible = calls
1723 .iter()
1724 .filter(|call| self.parallel_eligible(call))
1725 .count();
1726 let specialty: Vec<bool> = calls
1727 .iter()
1728 .map(|call| self.is_specialty_delegation(call))
1729 .collect();
1730 let any_specialty = specialty.contains(&true);
1731 if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
1732 let mut results = Vec::with_capacity(calls.len());
1734 for call in calls {
1735 results.push(if self.cancel.is_cancelled() {
1736 (not_executed(call, "cancelled"), Usage::default())
1737 } else {
1738 self.execute_tool(call, sid).await
1739 });
1740 }
1741 return results;
1742 }
1743
1744 let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
1745 let mut may_parallel = Vec::with_capacity(calls.len());
1746 for call in calls {
1747 let (result, parallel) = self.resolve_call(call, sid);
1748 settled.push(result.map(|result| (result, Usage::default())));
1749 may_parallel.push(parallel);
1750 }
1751 let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
1752 let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
1753 let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
1754
1755 if reads.len() > 1 {
1756 let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
1757 let handles: Vec<_> = reads
1758 .iter()
1759 .map(|&index| {
1760 (
1761 index,
1762 scope.spawn(move || self.dispatch(&calls[index], sid)),
1763 )
1764 })
1765 .collect();
1766 handles
1767 .into_iter()
1768 .map(|(index, handle)| {
1769 let result = handle
1770 .join()
1771 .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
1772 (index, result)
1773 })
1774 .collect()
1775 });
1776 for (index, result) in collected {
1777 settled[index] = Some((result, Usage::default()));
1778 }
1779 } else {
1780 for &index in &reads {
1781 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1782 }
1783 }
1784 let mut next = 0;
1788 while next < writes.len() {
1789 let index = writes[next];
1790 let run_end = writes[next..]
1791 .iter()
1792 .position(|&index| !specialty[index])
1793 .map_or(writes.len(), |offset| next + offset);
1794 if specialty[index] && run_end - next > 1 {
1795 let group: Vec<usize> = writes[next..run_end].to_vec();
1796 let results = if self.cancel.is_cancelled() {
1797 group
1798 .iter()
1799 .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
1800 .collect()
1801 } else {
1802 let members: Vec<&ToolCall> =
1803 group.iter().map(|&index| &calls[index]).collect();
1804 self.fan_out(&members, sid, spent)
1805 };
1806 for (index, result) in group.into_iter().zip(results) {
1807 settled[index] = Some(result);
1808 }
1809 next = run_end;
1810 } else {
1811 settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1812 next += 1;
1813 }
1814 }
1815
1816 settled
1817 .into_iter()
1818 .zip(calls)
1819 .map(|(result, call)| {
1820 result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
1821 })
1822 .collect()
1823 }
1824
1825 fn parallel_eligible(&self, call: &ToolCall) -> bool {
1828 call.invalid_arguments().is_none()
1829 && self
1830 .registry
1831 .get(&call.name)
1832 .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
1833 }
1834
1835 pub(crate) fn resolve_call(&self, call: &ToolCall, sid: &str) -> (Option<ToolResult>, bool) {
1844 let settled = |result: ToolResult| {
1845 self.record_tool_call(call, &result, sid);
1846 (Some(result), false)
1847 };
1848 if let Some(raw) = call.invalid_arguments() {
1849 return settled(invalid_arguments_result(call, raw));
1850 }
1851 let Some(tool) = self.registry.get(&call.name) else {
1852 return settled(self.registry.dispatch(call, &self.context));
1854 };
1855 if !self.context.scope_allows(&call.name) {
1858 return settled(self.registry.dispatch(call, &self.context));
1859 }
1860 let decision = self.gate.decide(tool.as_ref(), call, &self.context);
1861 if !decision.approved {
1862 return settled(not_executed(call, decision.reason));
1863 }
1864 (None, !tool.side_effecting() && tool.parallel_safe())
1865 }
1866
1867 async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1868 if self.cancel.is_cancelled() {
1869 (not_executed(call, "cancelled"), Usage::default())
1870 } else {
1871 self.dispatch_call(call, sid).await
1872 }
1873 }
1874
1875 async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1878 let request = match self.delegation(call, &self.context) {
1879 Some(request) => request,
1880 None => return (self.dispatch(call, sid), Usage::default()),
1881 };
1882 let mut span = self.tool_span(call);
1883 let (result, usage) = match request {
1884 Ok(request) => self.delegate(call, request, 1, &self.context).await,
1885 Err(invalid) => (invalid, Usage::default()),
1886 };
1887 span.set(vec![("tool.ok", json!(result.ok))]);
1888 self.tracer.end(span);
1889 self.record_tool_call(call, &result, sid);
1890 (result, usage)
1891 }
1892
1893 pub(crate) fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
1895 let mut span = self.tool_span(call);
1896 let result = self.registry.dispatch(call, &self.context);
1897 span.set(vec![("tool.ok", json!(result.ok))]);
1898 self.tracer.end(span);
1899 self.record_tool_call(call, &result, sid);
1900 result
1901 }
1902
1903 pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
1905 self.tracer.start(
1906 "tool_call",
1907 vec![
1908 ("tool.name", json!(call.name)),
1909 ("gen_ai.tool.name", json!(call.name)),
1910 ],
1911 )
1912 }
1913
1914 pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1915 self.recorder.event(
1916 sid,
1917 "tool_call",
1918 vec![
1919 ("tool", json!(call.name)),
1920 ("ok", json!(result.ok)),
1921 ("arguments", Value::Object(call.arguments.clone())),
1922 ("error", json!(result.error)),
1923 ],
1924 );
1925 self.record_repair(call, result, sid);
1926 }
1927
1928 pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1931 if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
1932 self.recorder.event(
1933 sid,
1934 "tool_args_repaired",
1935 vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
1936 );
1937 }
1938 }
1939
1940 pub(crate) fn repair_broken_calls(
1948 &self,
1949 calls: &mut [ToolCall],
1950 sid: &str,
1951 ) -> HashMap<String, String> {
1952 let mut notes = HashMap::new();
1953 for call in calls.iter_mut() {
1954 let Some(raw) = call.invalid_arguments() else {
1955 continue;
1956 };
1957 let Some((arguments, dropped)) = crate::broken_json::drop_unmatched_closers(raw) else {
1958 continue;
1959 };
1960 self.recorder.event(
1961 sid,
1962 "tool_args_repaired",
1963 vec![
1964 ("tool", json!(call.name)),
1965 (
1966 "dropped",
1967 json!(dropped
1968 .iter()
1969 .map(|(at, closer)| json!({"at": at, "char": closer.to_string()}))
1970 .collect::<Vec<_>>()),
1971 ),
1972 ],
1973 );
1974 notes.insert(call.id.clone(), repair_note(&dropped));
1975 call.arguments = arguments;
1976 }
1977 notes
1978 }
1979
1980 pub(crate) fn annotate_broken_json(
1985 &self,
1986 call: &ToolCall,
1987 result: ToolResult,
1988 repairs: &HashMap<String, String>,
1989 streak: &mut BrokenStreak,
1990 ) -> ToolResult {
1991 let mut result = result;
1992 if let Some(note) = repairs.get(&call.id) {
1993 append_note(&mut result, note);
1994 }
1995 if let Some(count) = streak.observe(call) {
1996 let mut advice = format!(
1997 "{count} calls in a row to {} have sent arguments that do not parse. Long, \
1998 deeply nested arguments break most often: send less in each call.",
1999 call.name
2000 );
2001 if let Some(hint) = self
2002 .registry
2003 .get(&call.name)
2004 .and_then(|tool| tool.retry_hint().map(str::to_owned))
2005 {
2006 advice.push(' ');
2007 advice.push_str(&hint);
2008 }
2009 append_note(&mut result, &advice);
2010 }
2011 result
2012 }
2013
2014 fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
2017 if self.guardrails.egress == EgressMode::Off {
2018 return;
2019 }
2020 for call in calls {
2021 let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
2022 let (report, _) = self.guardrails.inspect_egress(&payload);
2023 if report.flagged() {
2024 self.recorder.event(
2025 sid,
2026 "guardrail",
2027 vec![
2028 ("stage", json!("egress_tool_args")),
2029 ("tool", json!(call.name)),
2030 ("findings", json!(report.summary())),
2031 ],
2032 );
2033 }
2034 }
2035 }
2036
2037 async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
2039 match self.resolve_call(call, sid) {
2040 (Some(result), _) => (result, Usage::default()),
2041 (None, _) => self.dispatch_call(call, sid).await,
2042 }
2043 }
2044}
2045
2046#[derive(Debug, Default)]
2049pub(crate) struct BrokenStreak(HashMap<String, u32>);
2050
2051impl BrokenStreak {
2052 fn observe(&mut self, call: &ToolCall) -> Option<u32> {
2056 let count = self.0.entry(call.name.clone()).or_default();
2057 if call.invalid_arguments().is_none() {
2058 *count = 0;
2059 return None;
2060 }
2061 *count += 1;
2062 (*count >= 2).then_some(*count)
2063 }
2064}
2065
2066fn repair_note(dropped: &[(usize, char)]) -> String {
2068 let closers: Vec<String> = dropped
2069 .iter()
2070 .map(|(at, closer)| format!("`{closer}` at character {at}"))
2071 .collect();
2072 let noun = if dropped.len() == 1 {
2073 "closer"
2074 } else {
2075 "closers"
2076 };
2077 format!(
2078 "Note: these arguments were not valid JSON. agent86 dropped the unmatched {noun} {}, \
2079 which matched nothing, and ran the call with the rest. Check next time that every \
2080 bracket closes in order.",
2081 closers.join(", ")
2082 )
2083}
2084
2085fn append_note(result: &mut ToolResult, note: &str) {
2088 let text = if result.ok {
2089 &mut result.content
2090 } else {
2091 result.error.get_or_insert_with(String::new)
2092 };
2093 if !text.is_empty() {
2094 text.push_str("\n\n");
2095 }
2096 text.push_str(note);
2097}
2098
2099pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
2101 ToolResult {
2102 call_id: call.id.clone(),
2103 name: call.name.clone(),
2104 ok: false,
2105 content: String::new(),
2106 error: Some(format!("Not executed: {reason}.")),
2107 metadata: serde_json::Map::new(),
2108 }
2109}
2110
2111fn model_call_attributes(
2113 completion: Option<&crate::types::Completion>,
2114) -> Vec<(&'static str, Value)> {
2115 let Some(completion) = completion else {
2116 return vec![("agent86.completed", json!(false))];
2117 };
2118 let finish = completion
2119 .stop_reason
2120 .as_deref()
2121 .filter(|reason| !reason.is_empty())
2122 .map_or(Value::Null, |reason| json!([reason]));
2123 vec![
2124 ("agent86.completed", json!(true)),
2125 (
2126 "gen_ai.usage.input_tokens",
2127 json!(completion.usage.input_tokens),
2128 ),
2129 (
2130 "gen_ai.usage.output_tokens",
2131 json!(completion.usage.output_tokens),
2132 ),
2133 ("gen_ai.response.finish_reasons", finish),
2134 ("agent86.cost_usd", json!(completion.usage.cost_usd)),
2135 ("agent86.tool_calls", json!(completion.tool_calls.len())),
2136 ]
2137}
2138
2139fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
2142 let mut attributes = vec![("gen_ai.request.model", json!(model))];
2143 if let Some(summary) = &state.last_turn {
2144 attributes.extend([
2145 ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
2146 ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
2147 ("agent86.cost_usd", json!(summary.cost_usd)),
2148 ("agent86.steps", json!(summary.steps)),
2149 ("agent86.tool_calls", json!(summary.tool_calls)),
2150 ("agent86.duration_s", json!(summary.duration_s)),
2151 (
2152 "agent86.phase",
2153 serde_json::to_value(state.phase).unwrap_or(Value::Null),
2154 ),
2155 ]);
2156 }
2157 attributes
2158}
2159
2160fn record_step(state: &mut AgentState, step: Step) {
2162 state.usage = state.usage + step.usage;
2163 state.steps.push(step);
2164}
2165
2166fn message(role: Role, content: &str) -> Message {
2167 Message {
2168 role,
2169 content: content.to_owned(),
2170 tool_calls: Vec::new(),
2171 tool_call_id: None,
2172 name: None,
2173 }
2174}
2175
2176pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
2182 let preview = truncate_chars(raw, 200);
2183 let mut error = format!(
2184 "invalid JSON in tool arguments: {} could not be parsed. \
2185 Call the tool again with its arguments as a single valid JSON object.",
2186 python_repr(&preview)
2187 );
2188 if let Some(location) = crate::broken_json::describe(raw) {
2189 error.push('\n');
2190 error.push_str(&location);
2191 }
2192 ToolResult {
2193 call_id: call.id.clone(),
2194 name: call.name.clone(),
2195 ok: false,
2196 content: String::new(),
2197 error: Some(error),
2198 metadata: serde_json::Map::new(),
2199 }
2200}
2201
2202pub fn observation(result: &ToolResult) -> String {
2205 if result.ok {
2206 return result.content.clone();
2207 }
2208 let error = result.error.as_deref().unwrap_or_default().trim();
2209 let body = result.content.trim();
2210 match (error.is_empty(), body.is_empty()) {
2211 (false, false) => format!("{error}\n{body}"),
2212 (false, true) => error.to_owned(),
2213 (true, false) => body.to_owned(),
2214 (true, true) => "error".to_owned(),
2215 }
2216}
2217
2218pub(crate) fn request_temperature(provider: &dyn Provider, specialty: Option<f32>) -> f32 {
2221 specialty.or_else(|| provider.temperature()).unwrap_or(0.0)
2222}
2223
2224pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
2226 let text = python_json_dumps(&Value::Object(arguments.clone()), false);
2227 truncate_chars(&text, 160)
2228}
2229
2230pub fn summarize(result: &ToolResult) -> String {
2232 if !result.ok {
2233 let error = result.error.as_deref().unwrap_or_default().trim();
2234 let content = result.content.trim();
2235 let detail = [error, content, "(failed)"]
2236 .into_iter()
2237 .find(|text| !text.is_empty())
2238 .unwrap_or("(failed)");
2239 return format!("error: {}", first_chars(first_line(detail), 160));
2240 }
2241 let content = result.content.trim();
2242 let head = if content.is_empty() {
2243 "(no output)"
2244 } else {
2245 first_line(content)
2246 };
2247 first_chars(head, 160)
2248}
2249
2250fn first_line(text: &str) -> &str {
2252 let is_break = |c: char| {
2253 matches!(
2254 c,
2255 '\n' | '\r'
2256 | '\u{b}'
2257 | '\u{c}'
2258 | '\u{1c}'
2259 | '\u{1d}'
2260 | '\u{1e}'
2261 | '\u{85}'
2262 | '\u{2028}'
2263 | '\u{2029}'
2264 )
2265 };
2266 text.split(is_break).next().unwrap_or_default()
2267}
2268
2269fn first_chars(text: &str, limit: usize) -> String {
2270 text.chars().take(limit).collect()
2271}
2272
2273fn truncate_chars(text: &str, limit: usize) -> String {
2275 if text.chars().count() <= limit {
2276 text.to_owned()
2277 } else {
2278 format!("{} ...", first_chars(text, limit))
2279 }
2280}
2281
2282#[cfg(test)]
2283mod tests {
2284 use super::*;
2285 use serde_json::json;
2286
2287 fn limits() -> LimitsConfig {
2288 LimitsConfig {
2289 max_steps: 2,
2290 max_cost_usd: 1.0,
2291 max_wall_clock_s: 900,
2292 max_consecutive_errors: 1,
2293 max_context_tokens: 0,
2294 max_output_tokens: 8192,
2295 context_reserve_tokens: 4096,
2296 compaction: CompactionMode::Summarize,
2297 parallel_tools: true,
2298 tool_timeout_s: 60,
2299 context_sizing: true,
2300 stall_nudge: true,
2301 }
2302 }
2303
2304 #[test]
2305 fn the_breaker_trips_on_steps_cost_and_error_streaks() {
2306 let mut breaker = CircuitBreaker::new(&limits());
2307 breaker.before_step().unwrap();
2308 breaker.record_step(&Usage::default());
2309 breaker.record_step(&Usage::default());
2310 assert_eq!(
2311 breaker.before_step().unwrap_err().to_string(),
2312 "Circuit tripped: step budget reached (2 steps)"
2313 );
2314
2315 let mut costly = CircuitBreaker::new(&limits());
2316 costly.record_step(&Usage {
2317 cost_usd: 1.25,
2318 ..Usage::default()
2319 });
2320 assert_eq!(
2321 costly.before_step().unwrap_err().to_string(),
2322 "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
2323 );
2324
2325 let mut errors = CircuitBreaker::new(&limits());
2326 errors.record_tool_result(false).unwrap();
2327 errors.record_tool_result(true).unwrap();
2328 errors.record_tool_result(false).unwrap();
2329 assert_eq!(
2330 errors.record_tool_result(false).unwrap_err().to_string(),
2331 "Circuit tripped: aborted after 2 consecutive tool errors"
2332 );
2333 }
2334
2335 fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
2336 ToolResult {
2337 call_id: "c".to_owned(),
2338 name: "t".to_owned(),
2339 ok,
2340 content: content.to_owned(),
2341 error: error.map(str::to_owned),
2342 metadata: serde_json::Map::new(),
2343 }
2344 }
2345
2346 #[test]
2347 fn observations_keep_both_error_and_output() {
2348 assert_eq!(observation(&result(true, "data", None)), "data");
2349 assert_eq!(
2350 observation(&result(false, " out ", Some(" bad "))),
2351 "bad\nout"
2352 );
2353 assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
2354 assert_eq!(observation(&result(false, "", None)), "error");
2355 }
2356
2357 #[test]
2358 fn summaries_show_the_first_line() {
2359 assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
2360 assert_eq!(summarize(&result(true, " ", None)), "(no output)");
2361 assert_eq!(
2362 summarize(&result(false, "", Some("No such file: x\nmore"))),
2363 "error: No such file: x"
2364 );
2365 assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
2366 assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
2367 }
2368
2369 #[test]
2370 fn previews_use_python_json_and_cut_at_160_characters() {
2371 let Value::Object(short) = json!({"path": "src/main.rs"}) else {
2372 unreachable!()
2373 };
2374 assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
2375
2376 let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
2377 unreachable!()
2378 };
2379 let preview = preview_arguments(&long);
2380 assert!(preview.ends_with(" ..."));
2381 assert_eq!(preview.chars().count(), 164);
2382 }
2383
2384 #[test]
2385 fn invalid_json_is_reported_with_a_python_repr_preview() {
2386 let call = ToolCall {
2387 id: "c1".to_owned(),
2388 name: "read_file".to_owned(),
2389 arguments: serde_json::Map::new(),
2390 };
2391 let result = invalid_arguments_result(&call, "{\"path\": ");
2392 let error = result.error.as_deref().unwrap();
2393 assert_eq!(
2395 error.lines().next(),
2396 Some(
2397 "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
2398 Call the tool again with its arguments as a single valid JSON object."
2399 )
2400 );
2401 assert_eq!(
2402 error.lines().nth(1),
2403 Some(
2404 "The JSON ends at character 9 inside the top-level object, before it is \
2405 complete: EOF while parsing a value."
2406 )
2407 );
2408 assert!(!result.ok);
2409 assert_eq!(result.call_id, "c1");
2410 }
2411}