use crate::approval::ApprovalGate;
use crate::config::EgressMode;
use crate::config::{AgentsConfig, CompactionMode, LimitsConfig};
use crate::guardrails::Guardrails;
use crate::limits::LimitKind;
use crate::memory::sizing::{
aged_view, calibrated_budget, result_cap, shorten_middle, sized_reserve,
};
use crate::memory::working::{
apply_progress, apply_summary, compacted_notice, compaction_failed_notice, compaction_plan,
count_spec_tokens, count_tokens, fit_pinned, fits, python_strip, summary_request_text,
trimmed_notice, Cut, Fitted, KEEP_RECENT, SUMMARY_MAX_TOKENS, SUMMARY_RETRY_NOTE,
SUMMARY_SYSTEM_PROMPT,
};
use crate::observability::Recorder;
use crate::prompt::{time_note, with_turn_note, without_turn_note};
use crate::provider::reasoning::REASONING_LOOP;
use crate::provider::{Provider, ProviderError};
use crate::pyjson::{python_float_repr, python_json_dumps};
use crate::router::Router;
use crate::session::{AgentState, OpenTurn};
use crate::tools::{ToolContext, ToolRegistry};
use crate::turn::TurnSummary;
use crate::types::{
python_repr, AgentPhase, CompletionRequest, Message, Role, Step, ToolCall, ToolResult,
ToolSpec, Usage,
};
use crate::vault::StreamRedactor;
use futures_util::StreamExt;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
pub const MAX_CONTINUATIONS: u64 = 3;
const SUMMARY_MARGIN_TOKENS: u64 = 256;
const MIN_TRANSCRIPT_TOKENS: u64 = 1_024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SummaryError {
Cancelled,
Failed(String),
Empty,
}
#[derive(Debug, Clone)]
pub(crate) struct WrittenSummary {
pub outcome: Result<String, SummaryError>,
pub usage: Usage,
pub model: String,
}
struct Compaction {
notice: String,
summary: Option<String>,
}
struct TurnWindow<'g> {
goal_text: &'g str,
goal: usize,
continuation: Option<usize>,
retry_at: Option<u64>,
trim_announced: bool,
trimmed: usize,
aged: usize,
}
pub fn continuation_notice(index: u64) -> String {
format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
}
pub const ANSWER_PROMPT: &str =
"Your last reply was empty. Give the user your answer now, as plain text.";
pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
pub const REASONING_LOOP_NOTICE: &str =
"\n[the model's reasoning was repeating itself; stopped it]\n";
pub fn ollama_loop_hint(model: &str) -> String {
format!(
"[if Ollama keeps doing this, its runner may be stuck: \
`ollama stop {model}` unloads the model, and the next request loads it fresh]\n"
)
}
pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
pub const CONTINUED_NOTE: &str = "This turn stopped before it finished and is now continuing \
at the user's request. Time has passed: files and anything else your earlier tool calls \
looked at may have changed, and calls made just before the stop may have run without \
their results being recorded. Check the current state before relying on earlier results.";
pub const UNRECORDED_RESULT: &str =
"No result was recorded: the turn stopped before it was. The call may have run.";
pub fn continued_notice(steps: u32) -> String {
format!("[continuing the turn after step {steps}]\n")
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{0}")]
pub struct NotContinuable(pub String);
#[derive(Debug, Clone)]
pub struct Continuation {
open: OpenTurn,
goal_text: String,
skill: Option<Arc<crate::skills::Skill>>,
}
impl PartialEq for Continuation {
fn eq(&self, other: &Self) -> bool {
self.open == other.open
&& self.goal_text == other.goal_text
&& self.skill.as_ref().map(|skill| &skill.name)
== other.skill.as_ref().map(|skill| &skill.name)
}
}
impl Eq for Continuation {}
impl Continuation {
pub fn steps(&self) -> u32 {
self.open.steps
}
pub fn cost_usd(&self) -> f64 {
self.open.cost_usd
}
}
#[derive(Clone, Copy)]
enum Start<'a> {
New(&'a str),
Continue(&'a Continuation),
}
#[derive(Clone, Default)]
pub struct CancelToken {
inner: Arc<CancelInner>,
}
impl std::fmt::Debug for CancelToken {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CancelToken")
.field("cancelled", &self.is_cancelled())
.finish()
}
}
#[derive(Default)]
struct CancelInner {
flag: AtomicBool,
notify: tokio::sync::Notify,
}
impl CancelToken {
pub fn cancel(&self) {
self.inner.flag.store(true, Ordering::SeqCst);
self.inner.notify.notify_waiters();
}
pub fn is_cancelled(&self) -> bool {
self.inner.flag.load(Ordering::SeqCst)
}
pub fn clear(&self) {
self.inner.flag.store(false, Ordering::SeqCst);
}
pub async fn cancelled(&self) {
loop {
let notified = self.inner.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.is_cancelled() {
return;
}
notified.await;
}
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum TurnEvent<'a> {
Text(&'a str),
Notice(&'a str),
Thinking(&'a str),
ToolCall { call: &'a ToolCall, text: &'a str },
ToolResult {
call: &'a ToolCall,
result: &'a ToolResult,
observation: &'a str,
text: &'a str,
},
Usage {
step: &'a crate::types::Usage,
session: &'a crate::types::Usage,
},
Compacted {
notice: &'a str,
summary: Option<&'a str>,
},
#[cfg(feature = "agent86ui")]
Ui(&'a agent86_ui::AgentMessage),
}
impl<'a> TurnEvent<'a> {
pub fn text(&self) -> &'a str {
match *self {
Self::Text(text)
| Self::Notice(text)
| Self::ToolCall { text, .. }
| Self::ToolResult { text, .. }
| Self::Compacted { notice: text, .. } => text,
Self::Thinking(_) | Self::Usage { .. } => "",
#[cfg(feature = "agent86ui")]
Self::Ui(_) => "",
}
}
}
#[derive(Debug, Clone, PartialEq, Error)]
pub enum HarnessError {
#[error(transparent)]
Provider(#[from] ProviderError),
#[error("Circuit tripped: {0}")]
CircuitTripped(String),
#[error(
"The '{provider}' provider ended its stream for model {} without a final completion. \
The response was truncated; retry, or check the endpoint's streaming implementation.",
python_repr(model)
)]
NoFinalCompletion { provider: String, model: String },
}
impl HarnessError {
pub fn python_type(&self) -> &'static str {
match self {
Self::Provider(_) => "ProviderError",
Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
}
}
}
pub struct CircuitBreaker {
limits: LimitsConfig,
steps: u32,
cost_usd: f64,
consecutive_errors: u32,
started: Instant,
}
impl CircuitBreaker {
pub fn new(limits: &LimitsConfig) -> Self {
Self {
limits: limits.clone(),
steps: 0,
cost_usd: 0.0,
consecutive_errors: 0,
started: Instant::now(),
}
}
pub fn steps(&self) -> u32 {
self.steps
}
fn carry_over(&mut self, open: &OpenTurn) {
self.steps = open.steps;
self.cost_usd = open.cost_usd;
self.consecutive_errors = open.consecutive_errors;
}
pub fn max_steps(&self) -> u32 {
self.limits.max_steps
}
pub fn set_max_steps(&mut self, max_steps: u32) {
self.limits.max_steps = max_steps;
}
pub fn out_of_steps(&self) -> bool {
self.steps >= self.limits.max_steps
}
pub fn before_step(&self) -> Result<(), HarnessError> {
let limits = &self.limits;
if self.steps >= limits.max_steps {
return Err(trip(format!(
"step budget reached ({} steps)",
limits.max_steps
)));
}
if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
return Err(trip(format!(
"cost cap reached (${:.4} >= ${})",
self.cost_usd,
python_float_repr(limits.max_cost_usd)
)));
}
let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
return Err(trip(format!(
"wall-clock limit reached ({}s)",
limits.max_wall_clock_s
)));
}
Ok(())
}
pub fn record_step(&mut self, usage: &Usage) {
self.steps += 1;
self.cost_usd += usage.cost_usd;
}
pub fn cost(&self) -> f64 {
self.cost_usd
}
pub fn record_cost(&mut self, cost_usd: f64) {
self.cost_usd += cost_usd;
}
pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
if ok {
self.consecutive_errors = 0;
return Ok(());
}
self.consecutive_errors += 1;
if self.consecutive_errors > self.limits.max_consecutive_errors {
return Err(trip(format!(
"aborted after {} consecutive tool errors",
self.consecutive_errors
)));
}
Ok(())
}
}
fn trip(reason: String) -> HarnessError {
HarnessError::CircuitTripped(reason)
}
pub struct Harness {
pub provider: Arc<dyn Provider>,
pub router: Router,
pub tracer: crate::otel::Tracer,
pub registry: ToolRegistry,
pub context: ToolContext,
pub limits: LimitsConfig,
pub agents: AgentsConfig,
pub system: Message,
pub max_tokens: u32,
pub session_limits: crate::limits::SessionLimits,
pub context_window: u64,
pub gate: ApprovalGate,
pub guardrails: Guardrails,
pub recorder: Recorder,
pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
pub memory: Option<crate::session::SessionStore>,
pub cancel: CancelToken,
pub subagents: crate::subagent::SubagentState,
pub calibration: crate::memory::sizing::Calibration,
pub verify: crate::verify::Verify,
}
impl Harness {
pub(crate) fn system_message(&self) -> Message {
let offered = self.delegation_offered(&self.context, 0);
if let Some((persona, preloaded, _, _)) = self.subagents.main() {
return self.filtered_system(&persona, &self.context, &preloaded, offered, None);
}
self.system_for(&self.context, offered, None)
}
pub(crate) fn system_for(
&self,
ctx: &ToolContext,
delegation_offered: bool,
extra: Option<&str>,
) -> Message {
let mut system = self.system.clone();
if let Some(section) = self
.mcp
.as_ref()
.map(|mcp| mcp.prompt_section())
.filter(|section| !section.is_empty())
{
system.content = format!("{}\n\n{section}", system.content);
}
if delegation_offered {
if let Some(section) = self.specialty_listing(ctx) {
system.content = format!("{}\n\n{section}", system.content);
}
}
if let Some(section) = ctx.secrets.prompt_section() {
system.content = format!("{}\n\n{section}", system.content);
}
if crate::ask::reachable(ctx) && ctx.allowed_tool(crate::ask::ASK_USER) {
#[cfg(feature = "agent86ui")]
let drawing = ctx.ui.is_some() && ctx.allowed_tool(crate::agent86ui::RENDER_UI);
#[cfg(not(feature = "agent86ui"))]
let drawing = false;
system.content = format!(
"{}\n\n{}",
system.content,
crate::ask::prompt_section(drawing)
);
}
#[cfg(feature = "agent86ui")]
if let Some(ui) = ctx.ui.as_deref() {
if ctx.allowed_tool(crate::agent86ui::RENDER_UI) {
system.content = format!("{}\n\n{}", system.content, ui.prompt_section());
}
}
if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
system.content = format!("{}\n\n{extra}", system.content);
}
system
}
pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
self.context_budget_with(
system,
specs,
self.active_context_window(),
self.output_cap(),
self.active_provider().model(),
)
}
pub(crate) fn cap_result(&self, content: String, budget: u64) -> String {
if !self.limits.context_sizing {
return content;
}
shorten_middle(
&content,
result_cap(budget, self.context.policy.max_output_chars),
)
}
pub(crate) fn request_view(
&self,
messages: &[Message],
budget: u64,
) -> crate::memory::sizing::Aged {
if self.limits.context_sizing {
aged_view(messages, budget)
} else {
crate::memory::sizing::Aged {
messages: messages.to_vec(),
aged: 0,
}
}
}
pub(crate) fn context_budget_with(
&self,
system: &Message,
specs: &[ToolSpec],
window: u64,
output_cap: u32,
model: &str,
) -> u64 {
let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
let (ratio, reserve) = if self.limits.context_sizing {
(
self.calibration.ratio(model),
sized_reserve(self.limits.context_reserve_tokens, window),
)
} else {
(1.0, self.limits.context_reserve_tokens)
};
calibrated_budget(
window,
overhead,
reserve,
u64::from(output_cap),
self.limits.max_context_tokens,
ratio,
)
}
fn request_tools(&self) -> Vec<ToolSpec> {
let mut tools = self.registry.specs();
tools.retain(|spec| self.context.scope_allows(&spec.name));
tools
}
pub(crate) async fn write_summary(&self, messages: &[Message]) -> WrittenSummary {
let (summarizer, window) = self.summary_model();
let model = summarizer.model().to_owned();
let first_cap = SUMMARY_MAX_TOKENS * 2;
let share = |divisor: u64| u32::try_from(window / divisor).unwrap_or(u32::MAX);
let retry_cap = (SUMMARY_MAX_TOKENS * 8)
.min(share(4))
.max(first_cap.min(share(2)));
let instructions = message(Role::System, SUMMARY_SYSTEM_PROMPT);
let overhead = count_tokens(std::slice::from_ref(&instructions))
+ count_tokens(&[message(Role::User, SUMMARY_RETRY_NOTE)])
+ SUMMARY_MARGIN_TOKENS;
let room = window
.saturating_sub(overhead + u64::from(retry_cap))
.max(MIN_TRANSCRIPT_TOKENS);
let transcript =
summary_request_text(messages, usize::try_from(room * 4).unwrap_or(usize::MAX));
let mut usage = Usage::default();
let mut attempt = 0;
loop {
let (text, cap) = if attempt == 0 {
(transcript.clone(), first_cap)
} else {
(format!("{transcript}\n\n{SUMMARY_RETRY_NOTE}"), retry_cap)
};
let request = CompletionRequest {
model: model.clone(),
messages: vec![instructions.clone(), message(Role::User, &text)],
tools: Vec::new(),
temperature: 0.0,
max_tokens: Some(cap),
stream: false,
};
let completion = tokio::select! {
biased;
() = self.cancel.cancelled() => {
return WrittenSummary { outcome: Err(SummaryError::Cancelled), usage, model };
}
completion = summarizer.complete(request) => completion,
};
let completion = match completion {
Ok(completion) => completion,
Err(error) => {
return WrittenSummary {
outcome: Err(SummaryError::Failed(format!("ProviderError: {error}"))),
usage,
model,
}
}
};
usage = usage + completion.usage;
let text = python_strip(&completion.text).to_owned();
if !text.is_empty() {
return WrittenSummary {
outcome: Ok(text),
usage,
model,
};
}
if attempt > 0 {
return WrittenSummary {
outcome: Err(SummaryError::Empty),
usage,
model,
};
}
attempt += 1;
}
}
async fn compact_if_needed(
&self,
state: &mut AgentState,
summary: &mut TurnSummary,
breaker: &mut CircuitBreaker,
window: &mut TurnWindow<'_>,
) -> Option<Compaction> {
if self.limits.compaction != CompactionMode::Summarize {
return None;
}
let system = self.system_message();
let budget = self.context_budget(&system, &self.request_tools());
if fits(&self.request_view(&state.messages, budget).messages, budget) {
return None;
}
let tokens = count_tokens(&state.messages);
if window.retry_at.is_some_and(|at| tokens < at) {
return None;
}
let cut = compaction_plan(
&state.messages,
budget,
KEEP_RECENT,
window.goal,
window.continuation,
)?;
let sid = state.session_id.clone();
let end = cut.cut();
let replaced = cut.replaced();
let prefix = &state.messages[..end];
let dropped_tokens = count_tokens(prefix);
let written = self.write_summary(prefix).await;
summary.add_usage(&written.usage);
breaker.record_cost(written.usage.cost_usd);
let failed = |window: &mut TurnWindow<'_>, status: &str, error: Option<String>| {
window.retry_at = Some(tokens + (budget / 4).max(1));
let mut fields = vec![
("status", json!(status)),
("fallback", json!("drop")),
("dropped", json!(replaced)),
];
if let Some(error) = error {
fields.push(("error", json!(error)));
}
self.recorder.event(&sid, "compaction", fields);
Some(Compaction {
notice: compaction_failed_notice(replaced),
summary: None,
})
};
let text = match written.outcome {
Ok(text) => text,
Err(SummaryError::Cancelled) => return None,
Err(SummaryError::Failed(error)) => return failed(window, "failed", Some(error)),
Err(SummaryError::Empty) => return failed(window, "empty", None),
};
window.retry_at = None;
if let Some(memory) = &self.memory {
let _ = memory.record_compaction(&sid, &text, prefix);
}
let before = state.messages.len();
let kept = state.messages.split_off(end);
state.messages = match cut {
Cut::Earlier(_) => apply_summary(&text, kept),
Cut::WithinTurn { .. } => apply_progress(window.goal_text, &text, kept),
};
let removed = before - state.messages.len();
window.goal = match cut {
Cut::Earlier(_) => window.goal - removed,
Cut::WithinTurn { .. } => 0,
};
if let Some(start) = window.continuation.as_mut() {
*start -= removed;
}
if let Some(open) = state.open_turn.as_mut() {
open.goal = window.goal;
if matches!(cut, Cut::WithinTurn { .. }) {
open.goal_text = Some(window.goal_text.to_owned());
}
}
self.mark_open(state, breaker);
summary.compactions += 1;
let mut fields = vec![
("status", json!("ok")),
("dropped", json!(replaced)),
("dropped_tokens", json!(dropped_tokens)),
(
"summary_tokens",
json!(count_tokens(&[message(Role::User, &text)])),
),
("kept", json!(state.messages.len())),
("model", json!(written.model)),
];
if matches!(cut, Cut::WithinTurn { .. }) {
fields.push(("scope", json!("turn")));
}
self.recorder.event(&sid, "compaction", fields);
if let Some(memory) = &self.memory {
let _ = memory.persist(state);
}
Some(Compaction {
notice: compacted_notice(replaced),
summary: Some(text),
})
}
pub async fn run_turn(
&self,
state: &mut AgentState,
goal: &str,
on_text: impl FnMut(&str),
) -> Result<String, HarnessError> {
self.run_turn_as(state, goal, goal, on_text).await
}
pub async fn run_turn_as(
&self,
state: &mut AgentState,
user_text: &str,
display_text: &str,
mut on_text: impl FnMut(&str),
) -> Result<String, HarnessError> {
self.run_turn_events(state, user_text, display_text, |event| {
on_text(event.text())
})
.await
}
pub async fn run_turn_events(
&self,
state: &mut AgentState,
user_text: &str,
display_text: &str,
on_event: impl FnMut(TurnEvent<'_>),
) -> Result<String, HarnessError> {
self.run_turn_with(state, Start::New(user_text), display_text, None, on_event)
.await
}
pub async fn run_skill_turn(
&self,
state: &mut AgentState,
skill: &Arc<crate::skills::Skill>,
task: &str,
display_text: &str,
on_event: impl FnMut(TurnEvent<'_>),
) -> Result<String, HarnessError> {
let user_text = crate::skills::skill_request(skill, task);
self.run_turn_with(
state,
Start::New(&user_text),
display_text,
Some(skill),
on_event,
)
.await
}
pub fn continuable(&self, state: &AgentState) -> Result<Continuation, NotContinuable> {
let refuse = |why: &str| Err(NotContinuable(why.to_owned()));
let Some(open) = state
.open_turn
.clone()
.filter(|_| state.phase != AgentPhase::Done)
else {
return refuse(
"there is no unfinished turn to continue: the session's last turn finished",
);
};
let goal = state
.messages
.get(open.goal)
.filter(|goal| goal.role == Role::User);
let Some(goal) = goal.filter(|_| open.messages == state.messages.len()) else {
return refuse(
"the session's history has changed since its last turn stopped, so that turn \
can't be continued",
);
};
let goal_text = open
.goal_text
.clone()
.unwrap_or_else(|| goal.content.clone());
let skill = match &open.skill {
None => None,
Some(name) => match self.context.skills.get(name) {
Some(skill) => Some(Arc::clone(skill)),
None => {
return Err(NotContinuable(format!(
"the turn was running the skill '{name}', which is no longer available"
)))
}
},
};
let running = self.subagents.main_name();
if running != open.agent {
return Err(NotContinuable(match &open.agent {
Some(name) => format!(
"the turn ran as the specialist sub-agent '{name}'; continue it as that \
specialist (run --agent {name})"
),
None => "the turn did not run as a specialist sub-agent; continue it without one"
.to_owned(),
}));
}
Ok(Continuation {
open,
goal_text,
skill,
})
}
pub async fn continue_turn(
&self,
state: &mut AgentState,
continuation: &Continuation,
on_event: impl FnMut(TurnEvent<'_>),
) -> Result<String, HarnessError> {
let goal = without_turn_note(&continuation.goal_text).to_owned();
self.run_turn_with(
state,
Start::Continue(continuation),
&goal,
continuation.skill.as_ref(),
on_event,
)
.await
}
fn mark_open(&self, state: &mut AgentState, breaker: &CircuitBreaker) {
let messages = state.messages.len();
if let Some(open) = state.open_turn.as_mut() {
open.messages = messages;
open.steps = breaker.steps;
open.cost_usd = breaker.cost_usd;
open.consecutive_errors = breaker.consecutive_errors;
open.skill = self.context.active_skill().map(|skill| skill.name.clone());
}
}
async fn run_turn_with(
&self,
state: &mut AgentState,
start: Start<'_>,
display_text: &str,
skill: Option<&Arc<crate::skills::Skill>>,
on_event: impl FnMut(TurnEvent<'_>),
) -> Result<String, HarnessError> {
self.cancel.clear();
self.context.clear_skill();
if let Some(skill) = skill {
self.context.activate_skill(skill);
}
let started = Instant::now();
let mut span = self.tracer.start(
"turn",
vec![
("session.id", json!(state.session_id)),
(
"gen_ai.request.model",
json!(self.active_provider().model()),
),
],
);
let mut summary = TurnSummary::default();
let secrets = &self.context.secrets;
let display_text = secrets.redact(display_text);
let mut limits = self.limits.clone();
limits.max_steps = self.max_steps();
let mut breaker = CircuitBreaker::new(&limits);
let result = match start {
Start::New(user_text) => {
state.open_turn = None;
let user_text = secrets.redact(user_text);
self.turn(
state,
Start::New(&user_text),
&display_text,
&mut summary,
&mut breaker,
on_event,
)
.await
}
Start::Continue(continuation) => {
breaker.carry_over(&continuation.open);
state.open_turn = Some(continuation.open.clone());
self.turn(
state,
start,
&display_text,
&mut summary,
&mut breaker,
on_event,
)
.await
}
};
if state.phase == AgentPhase::Done {
state.open_turn = None;
} else {
self.mark_open(state, &breaker);
}
self.context.clear_skill();
summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
state.last_turn = Some(summary);
if let Err(error) = &result {
state.phase = AgentPhase::Error;
let reason = match error {
HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
HarnessError::Provider(detail) => {
format!("provider stream failed: ProviderError: {detail}")
}
HarnessError::NoFinalCompletion { .. } => {
"provider stream ended without a final completion".to_owned()
}
};
self.recorder.event(
&state.session_id,
"turn_end",
vec![("status", json!("error")), ("reason", json!(reason))],
);
}
span.set(turn_attributes(state, self.active_provider().model()));
if let Err(error) = &result {
span.fail(error.python_type(), &error.to_string());
}
self.tracer.end(span);
result
}
async fn turn(
&self,
state: &mut AgentState,
start: Start<'_>,
display_text: &str,
summary: &mut TurnSummary,
breaker: &mut CircuitBreaker,
mut on_event: impl FnMut(TurnEvent<'_>),
) -> Result<String, HarnessError> {
let (goal, continuing) = match start {
Start::New(goal) => (goal, None),
Start::Continue(continuation) => (
without_turn_note(&continuation.goal_text),
Some(continuation),
),
};
let mut output = String::new();
let mut emit = |event: TurnEvent<'_>| {
output.push_str(event.text());
on_event(event);
};
let sid = state.session_id.clone();
let mut fields = vec![("task", json!(display_text))];
if let Some(continuation) = continuing {
fields.push(("continued", json!(true)));
fields.push(("from_step", json!(continuation.open.steps)));
}
self.recorder.event(&sid, "turn_start", fields);
self.verify.set_last(None);
if let Some(continuation) = continuing {
emit(TurnEvent::Notice(&continued_notice(
continuation.open.steps,
)));
}
let report = match continuing {
None => self.guardrails.inspect_ingress(goal),
Some(_) => Default::default(),
};
if report.flagged() {
self.recorder.event(
&sid,
"guardrail",
vec![
("stage", json!("ingress_input")),
("findings", json!(report.summary())),
],
);
if self.guardrails.should_block(&report) {
let refusal = format!(
"Refused: input tripped the ingress guardrail ({}).",
report.summary()
);
state.messages.push(message(Role::User, goal));
state.messages.push(message(Role::Assistant, &refusal));
state.phase = AgentPhase::Error;
self.recorder
.event(&sid, "turn_end", vec![("status", json!("blocked"))]);
emit(TurnEvent::Text(&refusal));
return Ok(output);
}
emit(TurnEvent::Notice(&format!(
"[guardrail] input flagged: {}\n",
report.summary()
)));
}
let buffering = self.guardrails.egress == EgressMode::Redact;
self.route(goal, &sid)?;
let provider = self.active_provider();
let recall_note = self
.memory
.as_ref()
.and_then(|memory| memory.recall_note(goal));
let time = time_note(&jiff::ZonedDateTime::now());
let note = match recall_note {
Some(recalled) => format!("{time}\n\n{recalled}"),
None => time,
};
let (noted, continued_note) = match continuing {
None => (with_turn_note(goal, ¬e), None),
Some(continuation) => (
continuation.goal_text.clone(),
Some(format!("{note}\n\n{CONTINUED_NOTE}")),
),
};
let mut window = TurnWindow {
goal_text: ¬ed,
goal: continuing.map_or(state.messages.len(), |continuation| continuation.open.goal),
continuation: None,
retry_at: None,
trim_announced: false,
trimmed: 0,
aged: 0,
};
let base_steps = breaker.steps();
if continuing.is_none() {
state.messages.push(message(Role::User, ¬ed));
state.open_turn = Some(OpenTurn {
goal: window.goal,
messages: state.messages.len(),
skill: self.context.active_skill().map(|skill| skill.name.clone()),
agent: self.subagents.main_name(),
..OpenTurn::default()
});
} else {
let answered = answer_unrecorded(&mut state.messages, window.goal);
if answered > 0 {
self.mark_open(state, breaker);
}
}
let mut broken_streak = BrokenStreak::default();
let mut continuation_start: Option<usize> = None;
let mut continuation_parts: Vec<String> = Vec::new();
let mut nudged = false;
let mut ask_again = false;
let mut unanswered_thinking = String::new();
let mut reasoning_loops = 0u32;
let mut verify_run = crate::verify::VerifyRun::default();
if let Some(continuation) = continuing {
let taken = continuation.open.steps as usize;
for step in state.steps.iter().rev().take(taken) {
for result in &step.results {
verify_run.saw(&result.name, result.ok);
}
}
}
let mut stall = crate::stall::StallWatch::new(self.limits.stall_nudge);
loop {
if self.cancel.is_cancelled() {
self.cancelled(state, breaker.steps(), &mut emit);
return Ok(output);
}
if breaker.out_of_steps() {
match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
Some(raised) => breaker.set_max_steps(raised),
None if self.cancel.is_cancelled() => {
self.cancelled(state, breaker.steps(), &mut emit);
return Ok(output);
}
None => {}
}
}
breaker.before_step()?;
window.continuation = continuation_start;
if let Some(compaction) = self
.compact_if_needed(state, summary, breaker, &mut window)
.await
{
continuation_start = window.continuation;
window.trim_announced = compaction.summary.is_none();
emit(TurnEvent::Compacted {
notice: &compaction.notice,
summary: compaction.summary.as_deref(),
});
}
let estimated;
let step_budget;
let mut completion = {
let system = self.system_message();
let tools = self.request_tools();
let budget = self.context_budget(&system, &tools);
step_budget = budget;
let sent = request_goal(&state.messages, window.goal, continued_note.as_deref());
let aged = self.request_view(&sent, budget);
self.announce_age(&sid, aged.aged, budget, &mut window);
let fitted = fit_pinned(&aged.messages, budget, Some(window.goal));
self.announce_trim(&sid, &fitted, budget, &mut window, &mut emit);
let mut request_messages = Vec::with_capacity(fitted.messages.len() + 1);
request_messages.push(system);
request_messages.extend(fitted.messages);
if std::mem::take(&mut ask_again) {
request_messages.push(message(Role::User, ANSWER_PROMPT));
}
estimated = count_tokens(&request_messages) + count_spec_tokens(&tools);
let request = CompletionRequest {
model: provider.model().to_owned(),
messages: request_messages,
tools,
temperature: request_temperature(
provider.as_ref(),
self.subagents.main().and_then(|main| main.2),
),
max_tokens: Some(self.output_cap()),
stream: true,
};
let mut span = self.tracer.start(
"model_call",
vec![
("gen_ai.system", json!(provider.name())),
("gen_ai.request.model", json!(provider.model())),
("agent86.step", json!(breaker.steps() + 1)),
],
);
let mut stream = provider.stream(request);
let mut completion = None;
let mut buffered = String::new();
let mut redactor = StreamRedactor::default();
let mut thinking_redactor = StreamRedactor::default();
loop {
let next = tokio::select! {
biased;
() = self.cancel.cancelled() => None,
delta = stream.next() => Some(delta),
};
let Some(Some(delta)) = next else { break };
let delta = match delta {
Ok(delta) => delta,
Err(error) => {
span.set(model_call_attributes(None));
span.fail("ProviderError", &error.to_string());
self.tracer.end(span);
return Err(error.into());
}
};
if !delta.thinking.is_empty() && !buffering {
let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
if !shown.is_empty() {
emit(TurnEvent::Thinking(&shown));
}
}
if !delta.text.is_empty() {
if buffering {
buffered.push_str(&delta.text);
} else {
let shown = redactor.push(&self.context.secrets, &delta.text);
if !shown.is_empty() {
emit(TurnEvent::Text(&shown));
}
}
}
if delta.done && delta.completion.is_some() {
completion = delta.completion;
}
}
drop(stream);
let held = thinking_redactor.finish(&self.context.secrets);
if !held.is_empty() {
emit(TurnEvent::Thinking(&held));
}
let held = redactor.finish(&self.context.secrets);
if !held.is_empty() {
emit(TurnEvent::Text(&held));
}
span.set(model_call_attributes(completion.as_ref()));
self.tracer.end(span);
if self.cancel.is_cancelled() {
let partial = self
.guardrails
.inspect_egress(&self.context.secrets.redact(&buffered))
.1;
if !partial.is_empty() {
emit(TurnEvent::Text(&partial));
}
self.cancelled(state, breaker.steps(), &mut emit);
return Ok(output);
}
completion.ok_or_else(|| HarnessError::NoFinalCompletion {
provider: provider.name().to_owned(),
model: provider.model().to_owned(),
})?
};
breaker.record_step(&completion.usage);
if self.limits.context_sizing {
self.calibration.observe(
provider.model(),
estimated,
completion.usage.input_tokens,
);
}
summary.steps = u64::from(breaker.steps() - base_steps);
summary.add_usage(&completion.usage);
emit(TurnEvent::Usage {
step: &completion.usage,
session: &(state.usage + completion.usage),
});
let names: Vec<&str> = completion
.tool_calls
.iter()
.map(|call| call.name.as_str())
.collect();
self.recorder.event(
&sid,
"model_call",
vec![
("step", json!(breaker.steps())),
("model", json!(provider.model())),
("input_tokens", json!(completion.usage.input_tokens)),
("output_tokens", json!(completion.usage.output_tokens)),
("cost_usd", json!(completion.usage.cost_usd)),
("stop_reason", json!(completion.stop_reason)),
("tool_calls", json!(names)),
],
);
if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
reasoning_loops += 1;
if reasoning_loops == 2 && provider.name() == "ollama" {
emit(TurnEvent::Notice(&ollama_loop_hint(provider.model())));
}
}
let stopped = completion
.stop_reason
.as_deref()
.and_then(|reason| reason.strip_prefix(crate::provider::STOPPED_PREFIX))
.map(str::to_owned);
if let Some(reason) = &stopped {
emit(TurnEvent::Notice(&format!(
"\n[{} stopped the reply: {reason}]\n",
provider.name()
)));
}
let mut from_thinking = false;
if completion.tool_calls.is_empty()
&& completion.stop_reason.as_deref() != Some("max_tokens")
&& stopped.is_none()
&& completion.text.trim().is_empty()
&& continuation_start.is_none()
{
if !completion.thinking.trim().is_empty() {
unanswered_thinking = std::mem::take(&mut completion.thinking);
}
if !nudged && !breaker.out_of_steps() {
nudged = true;
ask_again = true;
self.recorder.event(
&sid,
"empty_answer",
vec![
("step", json!(breaker.steps())),
("model", json!(provider.model())),
("thinking_chars", json!(unanswered_thinking.chars().count())),
],
);
record_step(
state,
Step {
index: state.steps.len() as u64 + 1,
phase: AgentPhase::Execute,
thought: String::new(),
tool_calls: Vec::new(),
results: Vec::new(),
usage: completion.usage,
},
);
self.checkpoint(state, breaker);
emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
continue;
}
if unanswered_thinking.trim().is_empty() {
emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
if provider.name() == crate::provider::ServerKind::LmStudio.name() {
emit(TurnEvent::Notice(&format!(
"{}\n",
crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
)));
}
} else {
completion.text = std::mem::take(&mut unanswered_thinking);
from_thinking = true;
emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
}
}
let answer = self.context.secrets.redact(&completion.text);
let (egress, redacted) = self.guardrails.inspect_egress(&answer);
let text = if buffering {
if !redacted.is_empty() {
emit(TurnEvent::Text(&redacted));
}
redacted
} else {
if from_thinking {
emit(TurnEvent::Text(&answer));
}
answer
};
if egress.flagged() {
self.recorder.event(
&sid,
"guardrail",
vec![
("stage", json!("egress")),
("findings", json!(egress.summary())),
],
);
emit(TurnEvent::Notice(&format!(
"\n[guardrail] output flagged: {}\n",
egress.summary()
)));
}
let mut tool_calls = completion.tool_calls;
let repairs = self.repair_broken_calls(&mut tool_calls, &sid);
self.scan_tool_arguments(&tool_calls, &sid);
let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
if cut_off
&& tool_calls.is_empty()
&& text.trim().is_empty()
&& continuation_start.is_none()
{
let cap = self.output_cap();
if self
.raise_limit(LimitKind::Output, None, &sid, cap, false)
.is_some()
{
record_step(
state,
Step {
index: state.steps.len() as u64 + 1,
phase: AgentPhase::Execute,
thought: String::new(),
tool_calls: Vec::new(),
results: Vec::new(),
usage: completion.usage,
},
);
self.checkpoint(state, breaker);
continue;
}
}
let mut step = Step {
index: state.steps.len() as u64 + 1,
phase: AgentPhase::Execute,
thought: text.clone(),
tool_calls: tool_calls.clone(),
results: Vec::new(),
usage: completion.usage,
};
state.messages.push(Message {
tool_calls: tool_calls.clone(),
..message(Role::Assistant, &text)
});
if tool_calls.is_empty() {
if cut_off && summary.continuations < MAX_CONTINUATIONS {
summary.continuations += 1;
continuation_start.get_or_insert(state.messages.len() - 1);
continuation_parts.push(text);
state.messages.push(message(Role::User, CONTINUE_PROMPT));
record_step(state, step);
self.checkpoint(state, breaker);
self.recorder.event(
&sid,
"continuation",
vec![
("index", json!(summary.continuations)),
("step", json!(breaker.steps())),
("model", json!(provider.model())),
(
"chars",
json!(continuation_parts
.last()
.map_or(0, |part| part.chars().count())),
),
],
);
emit(TurnEvent::Notice(&continuation_notice(
summary.continuations,
)));
continue;
}
if let Some(start) = continuation_start.take() {
continuation_parts.push(text);
let joined = std::mem::take(&mut continuation_parts).concat();
state.messages.truncate(start);
state.messages.push(message(Role::Assistant, &joined));
step.thought = joined;
}
let steps_left = !breaker.out_of_steps();
if let crate::verify::Gate::SendBack(feedback) =
self.verify_answer(&mut verify_run, steps_left, &sid, &mut emit)
{
record_step(state, step);
state.messages.push(message(Role::User, &feedback));
self.checkpoint(state, breaker);
continue;
}
let outcome = step.thought.clone();
record_step(state, step);
state.phase = AgentPhase::Done;
self.recorder.event(
&sid,
"turn_end",
vec![
("status", json!("done")),
("steps", json!(breaker.steps())),
("continuations", json!(summary.continuations)),
],
);
if let Some(memory) = &self.memory {
let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
}
return Ok(output);
}
continuation_start = None;
continuation_parts.clear();
if self.cancel.is_cancelled() {
for call in &tool_calls {
let result = not_executed(call, "cancelled");
state.messages.push(Message {
tool_call_id: Some(call.id.clone()),
name: Some(call.name.clone()),
..message(Role::Tool, &observation(&result))
});
step.results.push(result);
}
record_step(state, step);
self.cancelled(state, breaker.steps(), &mut emit);
return Ok(output);
}
for call in &tool_calls {
let text = format!(
"\n[tool] {}({})\n",
call.name,
preview_arguments(&call.arguments)
);
emit(TurnEvent::ToolCall { call, text: &text });
}
let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
for notice in self.take_notices() {
emit(TurnEvent::Notice(&format!("{notice}\n")));
}
let mut asked_in_text: Option<String> = None;
let mut tripped: Option<HarnessError> = None;
for (call, (result, delegated)) in tool_calls.iter().zip(results) {
summary.tool_calls += 1;
if tripped.is_some() {
let content = self.observe(call, &result, step_budget, &sid);
emit(TurnEvent::ToolResult {
call,
result: &result,
observation: &content,
text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
});
state.messages.push(Message {
tool_call_id: Some(call.id.clone()),
name: Some(call.name.clone()),
..message(Role::Tool, &content)
});
step.results.push(result);
summary.add_usage(&delegated);
step.usage = step.usage + delegated;
breaker.record_cost(delegated.cost_usd);
continue;
}
#[cfg(feature = "agent86ui")]
let result = {
let mut result = result;
let (drawn, trace) = crate::agent86ui::take_drawn(&mut result.metadata);
for message in &drawn {
emit(TurnEvent::Ui(message));
}
if let Some(Value::Object(fields)) = trace {
let fields: Vec<(&str, Value)> = fields
.iter()
.map(|(key, value)| (key.as_str(), value.clone()))
.collect();
self.recorder.event(&sid, "ui_render", fields);
}
match crate::agent86ui::take_wait(&mut result.metadata) {
Some(surfaces) => self.ui_wait(call, result, surfaces, &sid),
None => result,
}
};
let mut result = self.ask_questions(call, result, &sid, &mut emit);
if let Some(Value::String(text)) = result.metadata.remove(crate::ask::ASK_TEXT_KEY)
{
asked_in_text = Some(match asked_in_text.take() {
Some(earlier) => format!("{earlier}\n\n{text}"),
None => text,
});
}
let result = self.annotate_broken_json(call, result, &repairs, &mut broken_streak);
summary.add_usage(&delegated);
step.usage = step.usage + delegated;
breaker.record_cost(delegated.cost_usd);
let content = self.observe(call, &result, step_budget, &sid);
emit(TurnEvent::ToolResult {
call,
result: &result,
observation: &content,
text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
});
state.messages.push(Message {
tool_call_id: Some(call.id.clone()),
name: Some(call.name.clone()),
..message(Role::Tool, &content)
});
let ok = result.ok;
verify_run.saw(&call.name, ok);
stall.saw(call, &result, &content);
step.results.push(result);
if let Err(error) = breaker.record_tool_result(ok) {
tripped = Some(error);
}
}
if let Some(error) = tripped {
record_step(state, step);
return Err(error);
}
if let Some(questions) = asked_in_text {
emit(TurnEvent::Text(&questions));
state.messages.push(message(Role::Assistant, &questions));
record_step(state, step);
state.phase = AgentPhase::Done;
self.recorder.event(
&sid,
"turn_end",
vec![
("status", json!("done")),
("steps", json!(breaker.steps())),
("continuations", json!(summary.continuations)),
],
);
if let Some(memory) = &self.memory {
let _ = memory.add_episode(&sid, goal, &questions, &Default::default());
}
return Ok(output);
}
if let Some(found) = stall.take() {
self.remind_of_stall(&found, &sid, &mut emit);
state.messages.push(message(Role::User, &found.note()));
}
record_step(state, step);
self.checkpoint(state, breaker);
if self.cancel.is_cancelled() {
self.cancelled(state, breaker.steps(), &mut emit);
return Ok(output);
}
}
}
fn checkpoint(&self, state: &mut AgentState, breaker: &CircuitBreaker) {
state.phase = AgentPhase::Execute;
self.mark_open(state, breaker);
if let Some(memory) = &self.memory {
let _ = memory.persist(state);
}
}
fn announce_trim(
&self,
sid: &str,
fitted: &Fitted,
budget: u64,
window: &mut TurnWindow<'_>,
emit: &mut impl FnMut(TurnEvent<'_>),
) {
if fitted.dropped == window.trimmed {
return;
}
window.trimmed = fitted.dropped;
if fitted.dropped == 0 {
return;
}
self.recorder.event(
sid,
"context_trim",
vec![
("dropped", json!(fitted.dropped)),
("kept", json!(fitted.messages.len())),
("budget", json!(budget)),
("goal_pinned", json!(fitted.pinned)),
],
);
if !window.trim_announced {
window.trim_announced = true;
emit(TurnEvent::Notice(&trimmed_notice(fitted.dropped)));
}
}
fn remind_of_stall(
&self,
found: &crate::stall::Stall,
sid: &str,
emit: &mut impl FnMut(TurnEvent<'_>),
) {
emit(TurnEvent::Notice(&found.notice()));
let mut fields = vec![
("shape", json!(found.kind.as_str())),
("count", json!(found.count)),
];
if let Some(tool) = &found.tool {
fields.push(("tool", json!(tool)));
}
self.recorder.event(sid, "stall", fields);
}
fn announce_age(&self, sid: &str, aged: usize, budget: u64, window: &mut TurnWindow<'_>) {
if aged == window.aged {
return;
}
window.aged = aged;
self.recorder.event(
sid,
"context_age",
vec![("aged", json!(aged)), ("budget", json!(budget))],
);
}
fn observe(&self, call: &ToolCall, result: &ToolResult, budget: u64, sid: &str) -> String {
let (content, findings) = self.guardrails.observe(observation(result));
let content = self.cap_result(content, budget);
if let Some(findings) = findings {
self.recorder.event(
sid,
"guardrail",
vec![
("stage", json!("observation")),
("tool", json!(call.name)),
("findings", json!(findings)),
],
);
}
content
}
fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
state.phase = AgentPhase::Error;
self.recorder.event(
&state.session_id,
"turn_end",
vec![
("status", json!("cancelled")),
("reason", json!("cancelled")),
("steps", json!(steps)),
],
);
emit(TurnEvent::Notice(CANCELLED_NOTICE));
}
async fn execute_batch(
&self,
calls: &[ToolCall],
sid: &str,
spent: f64,
) -> Vec<(ToolResult, Usage)> {
let eligible = calls
.iter()
.filter(|call| self.parallel_eligible(call))
.count();
let specialty: Vec<bool> = calls
.iter()
.map(|call| self.is_specialty_delegation(call))
.collect();
let any_specialty = specialty.contains(&true);
if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
let mut results = Vec::with_capacity(calls.len());
for call in calls {
results.push(if self.cancel.is_cancelled() {
(not_executed(call, "cancelled"), Usage::default())
} else {
self.execute_tool(call, sid).await
});
}
return results;
}
let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
let mut may_parallel = Vec::with_capacity(calls.len());
for call in calls {
let (result, parallel) = self.resolve_call(call, sid);
settled.push(result.map(|result| (result, Usage::default())));
may_parallel.push(parallel);
}
let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
if reads.len() > 1 {
let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
let handles: Vec<_> = reads
.iter()
.map(|&index| {
(
index,
scope.spawn(move || self.dispatch(&calls[index], sid)),
)
})
.collect();
handles
.into_iter()
.map(|(index, handle)| {
let result = handle
.join()
.unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
(index, result)
})
.collect()
});
for (index, result) in collected {
settled[index] = Some((result, Usage::default()));
}
} else {
for &index in &reads {
settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
}
}
let mut next = 0;
while next < writes.len() {
let index = writes[next];
let run_end = writes[next..]
.iter()
.position(|&index| !specialty[index])
.map_or(writes.len(), |offset| next + offset);
if specialty[index] && run_end - next > 1 {
let group: Vec<usize> = writes[next..run_end].to_vec();
let results = if self.cancel.is_cancelled() {
group
.iter()
.map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
.collect()
} else {
let members: Vec<&ToolCall> =
group.iter().map(|&index| &calls[index]).collect();
self.fan_out(&members, sid, spent)
};
for (index, result) in group.into_iter().zip(results) {
settled[index] = Some(result);
}
next = run_end;
} else {
settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
next += 1;
}
}
settled
.into_iter()
.zip(calls)
.map(|(result, call)| {
result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
})
.collect()
}
fn parallel_eligible(&self, call: &ToolCall) -> bool {
call.invalid_arguments().is_none()
&& self
.registry
.get(&call.name)
.is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
}
pub(crate) fn resolve_call(&self, call: &ToolCall, sid: &str) -> (Option<ToolResult>, bool) {
let settled = |result: ToolResult| {
self.record_tool_call(call, &result, sid);
(Some(result), false)
};
if let Some(raw) = call.invalid_arguments() {
return settled(invalid_arguments_result(call, raw));
}
let Some(tool) = self.registry.get(&call.name) else {
return settled(self.registry.dispatch(call, &self.context));
};
if !self.context.scope_allows(&call.name) {
return settled(self.registry.dispatch(call, &self.context));
}
let decision = self.gate.decide(tool.as_ref(), call, &self.context);
if !decision.approved {
return settled(not_executed(call, decision.reason));
}
(None, !tool.side_effecting() && tool.parallel_safe())
}
async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
if self.cancel.is_cancelled() {
(not_executed(call, "cancelled"), Usage::default())
} else {
self.dispatch_call(call, sid).await
}
}
async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
let request = match self.delegation(call, &self.context) {
Some(request) => request,
None => return (self.dispatch(call, sid), Usage::default()),
};
let mut span = self.tool_span(call);
let (result, usage) = match request {
Ok(request) => self.delegate(call, request, 1, &self.context).await,
Err(invalid) => (invalid, Usage::default()),
};
span.set(vec![("tool.ok", json!(result.ok))]);
self.tracer.end(span);
self.record_tool_call(call, &result, sid);
(result, usage)
}
pub(crate) fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
let mut span = self.tool_span(call);
let result = self.registry.dispatch(call, &self.context);
span.set(vec![("tool.ok", json!(result.ok))]);
self.tracer.end(span);
self.record_tool_call(call, &result, sid);
result
}
pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
self.tracer.start(
"tool_call",
vec![
("tool.name", json!(call.name)),
("gen_ai.tool.name", json!(call.name)),
],
)
}
pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
self.recorder.event(
sid,
"tool_call",
vec![
("tool", json!(call.name)),
("ok", json!(result.ok)),
("arguments", Value::Object(call.arguments.clone())),
("error", json!(result.error)),
],
);
self.record_repair(call, result, sid);
}
pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
self.recorder.event(
sid,
"tool_args_repaired",
vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
);
}
}
pub(crate) fn repair_broken_calls(
&self,
calls: &mut [ToolCall],
sid: &str,
) -> HashMap<String, String> {
let mut notes = HashMap::new();
for call in calls.iter_mut() {
let Some(raw) = call.invalid_arguments() else {
continue;
};
let Some((arguments, dropped)) = crate::broken_json::drop_unmatched_closers(raw) else {
continue;
};
self.recorder.event(
sid,
"tool_args_repaired",
vec![
("tool", json!(call.name)),
(
"dropped",
json!(dropped
.iter()
.map(|(at, closer)| json!({"at": at, "char": closer.to_string()}))
.collect::<Vec<_>>()),
),
],
);
notes.insert(call.id.clone(), repair_note(&dropped));
call.arguments = arguments;
}
notes
}
pub(crate) fn annotate_broken_json(
&self,
call: &ToolCall,
result: ToolResult,
repairs: &HashMap<String, String>,
streak: &mut BrokenStreak,
) -> ToolResult {
let mut result = result;
if let Some(note) = repairs.get(&call.id) {
append_note(&mut result, note);
}
if let Some(count) = streak.observe(call) {
let mut advice = format!(
"{count} calls in a row to {} have sent arguments that do not parse. Long, \
deeply nested arguments break most often: send less in each call.",
call.name
);
if let Some(hint) = self
.registry
.get(&call.name)
.and_then(|tool| tool.retry_hint().map(str::to_owned))
{
advice.push(' ');
advice.push_str(&hint);
}
append_note(&mut result, &advice);
}
result
}
fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
if self.guardrails.egress == EgressMode::Off {
return;
}
for call in calls {
let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
let (report, _) = self.guardrails.inspect_egress(&payload);
if report.flagged() {
self.recorder.event(
sid,
"guardrail",
vec![
("stage", json!("egress_tool_args")),
("tool", json!(call.name)),
("findings", json!(report.summary())),
],
);
}
}
}
async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
match self.resolve_call(call, sid) {
(Some(result), _) => (result, Usage::default()),
(None, _) => self.dispatch_call(call, sid).await,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct BrokenStreak(HashMap<String, u32>);
impl BrokenStreak {
fn observe(&mut self, call: &ToolCall) -> Option<u32> {
let count = self.0.entry(call.name.clone()).or_default();
if call.invalid_arguments().is_none() {
*count = 0;
return None;
}
*count += 1;
(*count >= 2).then_some(*count)
}
}
fn repair_note(dropped: &[(usize, char)]) -> String {
let closers: Vec<String> = dropped
.iter()
.map(|(at, closer)| format!("`{closer}` at character {at}"))
.collect();
let noun = if dropped.len() == 1 {
"closer"
} else {
"closers"
};
format!(
"Note: these arguments were not valid JSON. agent86 dropped the unmatched {noun} {}, \
which matched nothing, and ran the call with the rest. Check next time that every \
bracket closes in order.",
closers.join(", ")
)
}
fn append_note(result: &mut ToolResult, note: &str) {
let text = if result.ok {
&mut result.content
} else {
result.error.get_or_insert_with(String::new)
};
if !text.is_empty() {
text.push_str("\n\n");
}
text.push_str(note);
}
fn request_goal<'m>(
messages: &'m [Message],
goal: usize,
note: Option<&str>,
) -> std::borrow::Cow<'m, [Message]> {
match note {
Some(note) if goal < messages.len() => {
let mut sent = messages.to_vec();
sent[goal].content = with_turn_note(&sent[goal].content, note);
std::borrow::Cow::Owned(sent)
}
_ => std::borrow::Cow::Borrowed(messages),
}
}
fn answer_unrecorded(messages: &mut Vec<Message>, from: usize) -> usize {
let mut answered = 0;
let mut index = from;
while index < messages.len() {
if messages[index].role != Role::Assistant || messages[index].tool_calls.is_empty() {
index += 1;
continue;
}
let mut pending = messages[index].tool_calls.clone();
let mut end = index + 1;
while end < messages.len() && messages[end].role == Role::Tool {
let id = messages[end].tool_call_id.as_deref();
pending.retain(|call| Some(call.id.as_str()) != id);
end += 1;
}
for call in pending {
let result = ToolResult {
error: Some(UNRECORDED_RESULT.to_owned()),
..not_executed(&call, "")
};
messages.insert(
end,
Message {
tool_call_id: Some(call.id.clone()),
name: Some(call.name.clone()),
..message(Role::Tool, &observation(&result))
},
);
end += 1;
answered += 1;
}
index = end;
}
answered
}
pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
ToolResult {
call_id: call.id.clone(),
name: call.name.clone(),
ok: false,
content: String::new(),
error: Some(format!("Not executed: {reason}.")),
metadata: serde_json::Map::new(),
}
}
fn model_call_attributes(
completion: Option<&crate::types::Completion>,
) -> Vec<(&'static str, Value)> {
let Some(completion) = completion else {
return vec![("agent86.completed", json!(false))];
};
let finish = completion
.stop_reason
.as_deref()
.filter(|reason| !reason.is_empty())
.map_or(Value::Null, |reason| json!([reason]));
vec![
("agent86.completed", json!(true)),
(
"gen_ai.usage.input_tokens",
json!(completion.usage.input_tokens),
),
(
"gen_ai.usage.output_tokens",
json!(completion.usage.output_tokens),
),
("gen_ai.response.finish_reasons", finish),
("agent86.cost_usd", json!(completion.usage.cost_usd)),
("agent86.tool_calls", json!(completion.tool_calls.len())),
]
}
fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
let mut attributes = vec![("gen_ai.request.model", json!(model))];
if let Some(summary) = &state.last_turn {
attributes.extend([
("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
("agent86.cost_usd", json!(summary.cost_usd)),
("agent86.steps", json!(summary.steps)),
("agent86.tool_calls", json!(summary.tool_calls)),
("agent86.duration_s", json!(summary.duration_s)),
(
"agent86.phase",
serde_json::to_value(state.phase).unwrap_or(Value::Null),
),
]);
}
attributes
}
fn record_step(state: &mut AgentState, step: Step) {
state.usage = state.usage + step.usage;
state.steps.push(step);
}
fn message(role: Role, content: &str) -> Message {
Message {
role,
content: content.to_owned(),
tool_calls: Vec::new(),
tool_call_id: None,
name: None,
}
}
pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
let preview = truncate_chars(raw, 200);
let mut error = format!(
"invalid JSON in tool arguments: {} could not be parsed. \
Call the tool again with its arguments as a single valid JSON object.",
python_repr(&preview)
);
if let Some(location) = crate::broken_json::describe(raw) {
error.push('\n');
error.push_str(&location);
}
ToolResult {
call_id: call.id.clone(),
name: call.name.clone(),
ok: false,
content: String::new(),
error: Some(error),
metadata: serde_json::Map::new(),
}
}
pub fn observation(result: &ToolResult) -> String {
if result.ok {
return result.content.clone();
}
let error = result.error.as_deref().unwrap_or_default().trim();
let body = result.content.trim();
match (error.is_empty(), body.is_empty()) {
(false, false) => format!("{error}\n{body}"),
(false, true) => error.to_owned(),
(true, false) => body.to_owned(),
(true, true) => "error".to_owned(),
}
}
pub(crate) fn request_temperature(provider: &dyn Provider, specialty: Option<f32>) -> f32 {
specialty.or_else(|| provider.temperature()).unwrap_or(0.0)
}
pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
let text = python_json_dumps(&Value::Object(arguments.clone()), false);
truncate_chars(&text, 160)
}
pub fn summarize(result: &ToolResult) -> String {
if !result.ok {
let error = result.error.as_deref().unwrap_or_default().trim();
let content = result.content.trim();
let detail = [error, content, "(failed)"]
.into_iter()
.find(|text| !text.is_empty())
.unwrap_or("(failed)");
return format!("error: {}", first_chars(first_line(detail), 160));
}
let content = result.content.trim();
let head = if content.is_empty() {
"(no output)"
} else {
first_line(content)
};
first_chars(head, 160)
}
fn first_line(text: &str) -> &str {
let is_break = |c: char| {
matches!(
c,
'\n' | '\r'
| '\u{b}'
| '\u{c}'
| '\u{1c}'
| '\u{1d}'
| '\u{1e}'
| '\u{85}'
| '\u{2028}'
| '\u{2029}'
)
};
text.split(is_break).next().unwrap_or_default()
}
fn first_chars(text: &str, limit: usize) -> String {
text.chars().take(limit).collect()
}
fn truncate_chars(text: &str, limit: usize) -> String {
if text.chars().count() <= limit {
text.to_owned()
} else {
format!("{} ...", first_chars(text, limit))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn limits() -> LimitsConfig {
LimitsConfig {
max_steps: 2,
max_cost_usd: 1.0,
max_wall_clock_s: 900,
max_consecutive_errors: 1,
max_context_tokens: 0,
max_output_tokens: 8192,
context_reserve_tokens: 4096,
compaction: CompactionMode::Summarize,
parallel_tools: true,
tool_timeout_s: 60,
context_sizing: true,
stall_nudge: true,
}
}
#[test]
fn the_breaker_trips_on_steps_cost_and_error_streaks() {
let mut breaker = CircuitBreaker::new(&limits());
breaker.before_step().unwrap();
breaker.record_step(&Usage::default());
breaker.record_step(&Usage::default());
assert_eq!(
breaker.before_step().unwrap_err().to_string(),
"Circuit tripped: step budget reached (2 steps)"
);
let mut costly = CircuitBreaker::new(&limits());
costly.record_step(&Usage {
cost_usd: 1.25,
..Usage::default()
});
assert_eq!(
costly.before_step().unwrap_err().to_string(),
"Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
);
let mut errors = CircuitBreaker::new(&limits());
errors.record_tool_result(false).unwrap();
errors.record_tool_result(true).unwrap();
errors.record_tool_result(false).unwrap();
assert_eq!(
errors.record_tool_result(false).unwrap_err().to_string(),
"Circuit tripped: aborted after 2 consecutive tool errors"
);
}
fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
ToolResult {
call_id: "c".to_owned(),
name: "t".to_owned(),
ok,
content: content.to_owned(),
error: error.map(str::to_owned),
metadata: serde_json::Map::new(),
}
}
#[test]
fn observations_keep_both_error_and_output() {
assert_eq!(observation(&result(true, "data", None)), "data");
assert_eq!(
observation(&result(false, " out ", Some(" bad "))),
"bad\nout"
);
assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
assert_eq!(observation(&result(false, "", None)), "error");
}
#[test]
fn summaries_show_the_first_line() {
assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
assert_eq!(summarize(&result(true, " ", None)), "(no output)");
assert_eq!(
summarize(&result(false, "", Some("No such file: x\nmore"))),
"error: No such file: x"
);
assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
}
#[test]
fn previews_use_python_json_and_cut_at_160_characters() {
let Value::Object(short) = json!({"path": "src/main.rs"}) else {
unreachable!()
};
assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
unreachable!()
};
let preview = preview_arguments(&long);
assert!(preview.ends_with(" ..."));
assert_eq!(preview.chars().count(), 164);
}
#[test]
fn invalid_json_is_reported_with_a_python_repr_preview() {
let call = ToolCall {
id: "c1".to_owned(),
name: "read_file".to_owned(),
arguments: serde_json::Map::new(),
};
let result = invalid_arguments_result(&call, "{\"path\": ");
let error = result.error.as_deref().unwrap();
assert_eq!(
error.lines().next(),
Some(
"invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
Call the tool again with its arguments as a single valid JSON object."
)
);
assert_eq!(
error.lines().nth(1),
Some(
"The JSON ends at character 9 inside the top-level object, before it is \
complete: EOF while parsing a value."
)
);
assert!(!result.ok);
assert_eq!(result.call_id, "c1");
}
}