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