Skip to main content

agent86_core/
agent.rs

1//! The ReAct loop, ported from Python's `orchestration/loop.py` and
2//! `orchestration/circuit.py`.
3//!
4//! One user turn: call the model, run the tools it asks for, feed the results
5//! back, and repeat until it answers without tools. A circuit breaker bounds the
6//! turn by steps, cost, wall-clock time, and consecutive tool errors. Tool
7//! activity is reported inline as `[tool] ...` lines, exactly as Python streams it.
8//!
9//! Side-effecting calls pass through the approval gate before they run.
10//!
11//! Guardrails scan the goal, each answer, and each tool observation.
12//!
13//! A turn can be cancelled from another thread or task ([`CancelToken`]). It stops at
14//! the next safe point: before a model call, while a response streams, and between
15//! tool calls, never in the middle of one. The partial exchange is kept.
16//!
17//! Every request is fitted to the model's context window (`memory::working`).
18//! Before a model call, a conversation over budget has its oldest span replaced
19//! by a model-written summary (`[limits] compaction = "summarize"`), or dropped.
20//!
21//! `delegate` runs a sub-agent (`crate::subagent`) inside the batch's sequential
22//! part, and what it spends is added to the turn.
23
24use crate::approval::ApprovalGate;
25use crate::config::EgressMode;
26use crate::config::{AgentsConfig, CompactionMode, LimitsConfig};
27use crate::guardrails::Guardrails;
28use crate::limits::LimitKind;
29use crate::memory::sizing::{
30    aged_view, calibrated_budget, result_cap, shorten_middle, sized_reserve,
31};
32use crate::memory::working::{
33    apply_progress, apply_summary, compacted_notice, compaction_failed_notice, compaction_plan,
34    count_spec_tokens, count_tokens, fit_pinned, fits, python_strip, summary_request_text,
35    trimmed_notice, Cut, Fitted, KEEP_RECENT, SUMMARY_MAX_TOKENS, SUMMARY_RETRY_NOTE,
36    SUMMARY_SYSTEM_PROMPT,
37};
38use crate::observability::Recorder;
39use crate::prompt::time_note;
40use crate::provider::reasoning::REASONING_LOOP;
41use crate::provider::{Provider, ProviderError};
42use crate::pyjson::{python_float_repr, python_json_dumps};
43use crate::router::Router;
44use crate::session::AgentState;
45use crate::tools::{ToolContext, ToolRegistry};
46use crate::turn::TurnSummary;
47use crate::types::{
48    python_repr, AgentPhase, CompletionRequest, Message, Role, Step, ToolCall, ToolResult,
49    ToolSpec, Usage,
50};
51use crate::vault::StreamRedactor;
52use futures_util::StreamExt;
53use serde_json::{json, Value};
54use std::collections::HashMap;
55use std::sync::atomic::{AtomicBool, Ordering};
56use std::sync::Arc;
57use std::time::{Duration, Instant};
58use thiserror::Error;
59
60/// What the harness says to a model that ran out of output tokens mid-answer.
61pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
62
63/// How many times one turn may ask for more after hitting the output cap.
64pub const MAX_CONTINUATIONS: u64 = 3;
65
66/// Tokens held back in a summary request for the chat template and the
67/// estimate's error, beyond Python.
68const SUMMARY_MARGIN_TOKENS: u64 = 256;
69
70/// The least transcript a summary request is given, however small the window.
71const MIN_TRANSCRIPT_TOKENS: u64 = 1_024;
72
73/// Why [`Harness::write_summary`] wrote nothing.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum SummaryError {
76    Cancelled,
77    /// The provider failed; the text is what the trace records.
78    Failed(String),
79    /// Both attempts came back empty.
80    Empty,
81}
82
83/// What [`Harness::write_summary`] produced, and what it spent doing so.
84#[derive(Debug, Clone)]
85pub(crate) struct WrittenSummary {
86    pub outcome: Result<String, SummaryError>,
87    pub usage: Usage,
88    pub model: String,
89}
90
91/// A compaction to announce: the notice, and the summary when one was written.
92struct Compaction {
93    notice: String,
94    summary: Option<String>,
95}
96
97/// What a turn keeps about its place in the history while it fits and
98/// compacts it, beyond Python.
99struct TurnWindow<'g> {
100    /// The turn's message as the user sent it, kept verbatim through compactions.
101    goal_text: &'g str,
102    /// Where the turn's message is in the history.
103    goal: usize,
104    /// Where a continuation in progress began; compaction never reaches it.
105    continuation: Option<usize>,
106    /// After a failed summary, the history size at which one is tried again.
107    retry_at: Option<u64>,
108    /// Whether this turn has said that fitting leaves messages out.
109    trim_announced: bool,
110    /// How many messages the last request left out.
111    trimmed: usize,
112    /// How many tool results the last request sent aged (`crate::memory::sizing`).
113    aged: usize,
114}
115
116/// The user-visible line announcing continuation `index`.
117pub fn continuation_notice(index: u64) -> String {
118    format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
119}
120
121/// What the harness asks, once, of a model whose final reply was empty. Beyond Python.
122pub const ANSWER_PROMPT: &str =
123    "Your last reply was empty. Give the user your answer now, as plain text.";
124
125/// Said when an empty final reply is sent back for an answer.
126pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
127
128/// Said when the model still gave no answer and its reasoning is shown instead.
129pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
130
131/// Said when the model still gave no answer and had no reasoning to show.
132pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
133
134/// Said when the provider stopped a reply whose reasoning kept repeating itself.
135/// Beyond Python.
136pub const REASONING_LOOP_NOTICE: &str =
137    "\n[the model's reasoning was repeating itself; stopped it]\n";
138
139/// What a cancelled turn says, as Python's `_cancelled`.
140pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
141
142/// Asks the in-flight turn to stop at its next safe point, as Python's `Harness.cancel`.
143///
144/// Clones share one flag, so a signal handler or another task can hold one. Cancelling
145/// when no turn is running is harmless: every turn clears the flag on entry.
146#[derive(Clone, Default)]
147pub struct CancelToken {
148    inner: Arc<CancelInner>,
149}
150
151impl std::fmt::Debug for CancelToken {
152    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        formatter
154            .debug_struct("CancelToken")
155            .field("cancelled", &self.is_cancelled())
156            .finish()
157    }
158}
159
160#[derive(Default)]
161struct CancelInner {
162    flag: AtomicBool,
163    notify: tokio::sync::Notify,
164}
165
166impl CancelToken {
167    pub fn cancel(&self) {
168        self.inner.flag.store(true, Ordering::SeqCst);
169        self.inner.notify.notify_waiters();
170    }
171
172    pub fn is_cancelled(&self) -> bool {
173        self.inner.flag.load(Ordering::SeqCst)
174    }
175
176    pub fn clear(&self) {
177        self.inner.flag.store(false, Ordering::SeqCst);
178    }
179
180    /// Resolves once [`CancelToken::cancel`] has been called.
181    pub async fn cancelled(&self) {
182        loop {
183            let notified = self.inner.notify.notified();
184            tokio::pin!(notified);
185            // Registered before the flag is read, so a cancel in between is not missed.
186            notified.as_mut().enable();
187            if self.is_cancelled() {
188                return;
189            }
190            notified.await;
191        }
192    }
193}
194
195/// One thing a running turn reports. Each event carries the text that `run` and the
196/// plain REPL stream for it, so every surface sees the same output.
197///
198/// `#[non_exhaustive]` (since 1.2.0, ADR 0004): later releases add kinds of event,
199/// so a `match` outside this crate needs a `_` arm. [`TurnEvent::text`] is what any
200/// event adds to the turn's output, whatever its kind.
201#[derive(Debug, Clone, Copy)]
202#[non_exhaustive]
203pub enum TurnEvent<'a> {
204    /// The model's text (or the ingress guardrail's refusal, which stands in for it).
205    Text(&'a str),
206    /// A notice from the harness (`[cancelled]`, `[guardrail] ...`, a continuation or
207    /// compaction note): part of the output, but never part of the answer, so `run`
208    /// can keep it off stdout.
209    Notice(&'a str),
210    /// A piece of the model's reasoning, already redacted. Not part of the turn's
211    /// output: only the interface shows it.
212    Thinking(&'a str),
213    /// A tool call, announced before its batch runs; `text` is its `[tool] name(...)` line.
214    ToolCall { call: &'a ToolCall, text: &'a str },
215    /// A call's result, in call order. `observation` is what the model is shown, after
216    /// the observation guardrail; `text` is the `[tool] name -> summary` line.
217    ToolResult {
218        call: &'a ToolCall,
219        result: &'a ToolResult,
220        observation: &'a str,
221        text: &'a str,
222    },
223    /// Beyond Python: a model call finished. `step` is what it used; `session` is
224    /// the session's usage with it added (sub-agents' spend joins when their batch
225    /// ends). Adds nothing to the turn's output.
226    Usage {
227        step: &'a crate::types::Usage,
228        session: &'a crate::types::Usage,
229    },
230    /// The history was compacted: `notice` is what the other surfaces stream (a
231    /// notice, as before), and `summary` the summary written, `None` when it could
232    /// not be and the history was trimmed instead (beyond Python: an editor shows it
233    /// as ACP's `compaction_update`).
234    Compacted {
235        notice: &'a str,
236        summary: Option<&'a str>,
237    },
238    /// Beyond Python (ADR 0005): one A2UI message a `render_ui` call drew,
239    /// validated, for the surface to draw. Sent after the call's `ToolCall` and
240    /// before its `ToolResult`, in order. Adds nothing to the turn's output.
241    #[cfg(feature = "agent86ui")]
242    Ui(&'a agent86_ui::AgentMessage),
243}
244
245impl<'a> TurnEvent<'a> {
246    /// The text this event adds to the turn's output.
247    pub fn text(&self) -> &'a str {
248        match *self {
249            Self::Text(text)
250            | Self::Notice(text)
251            | Self::ToolCall { text, .. }
252            | Self::ToolResult { text, .. }
253            | Self::Compacted { notice: text, .. } => text,
254            Self::Thinking(_) | Self::Usage { .. } => "",
255            #[cfg(feature = "agent86ui")]
256            Self::Ui(_) => "",
257        }
258    }
259}
260
261/// A turn could not be completed.
262#[derive(Debug, Clone, PartialEq, Error)]
263pub enum HarnessError {
264    #[error(transparent)]
265    Provider(#[from] ProviderError),
266
267    #[error("Circuit tripped: {0}")]
268    CircuitTripped(String),
269
270    #[error(
271        "The '{provider}' provider ended its stream for model {} without a final completion. \
272         The response was truncated; retry, or check the endpoint's streaming implementation.",
273        python_repr(model)
274    )]
275    NoFinalCompletion { provider: String, model: String },
276}
277
278impl HarnessError {
279    /// The name of the exception Python raises for this failure, which its
280    /// full-screen interface shows (`error: ProviderError: ...`).
281    pub fn python_type(&self) -> &'static str {
282        match self {
283            Self::Provider(_) => "ProviderError",
284            Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
285        }
286    }
287}
288
289/// Bounds one turn: steps, cumulative cost, wall-clock time, and the tool-error streak.
290pub struct CircuitBreaker {
291    limits: LimitsConfig,
292    steps: u32,
293    cost_usd: f64,
294    consecutive_errors: u32,
295    started: Instant,
296}
297
298impl CircuitBreaker {
299    pub fn new(limits: &LimitsConfig) -> Self {
300        Self {
301            limits: limits.clone(),
302            steps: 0,
303            cost_usd: 0.0,
304            consecutive_errors: 0,
305            started: Instant::now(),
306        }
307    }
308
309    pub fn steps(&self) -> u32 {
310        self.steps
311    }
312
313    /// The step budget.
314    pub fn max_steps(&self) -> u32 {
315        self.limits.max_steps
316    }
317
318    /// Raise (or lower) the step budget mid-run, when the user raises it.
319    pub fn set_max_steps(&mut self, max_steps: u32) {
320        self.limits.max_steps = max_steps;
321    }
322
323    /// The step budget is spent, so the next [`CircuitBreaker::before_step`] trips.
324    pub fn out_of_steps(&self) -> bool {
325        self.steps >= self.limits.max_steps
326    }
327
328    /// Fail if starting another model call would breach a bound.
329    pub fn before_step(&self) -> Result<(), HarnessError> {
330        let limits = &self.limits;
331        if self.steps >= limits.max_steps {
332            return Err(trip(format!(
333                "step budget reached ({} steps)",
334                limits.max_steps
335            )));
336        }
337        if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
338            return Err(trip(format!(
339                "cost cap reached (${:.4} >= ${})",
340                self.cost_usd,
341                python_float_repr(limits.max_cost_usd)
342            )));
343        }
344        let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
345        if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
346            return Err(trip(format!(
347                "wall-clock limit reached ({}s)",
348                limits.max_wall_clock_s
349            )));
350        }
351        Ok(())
352    }
353
354    pub fn record_step(&mut self, usage: &Usage) {
355        self.steps += 1;
356        self.cost_usd += usage.cost_usd;
357    }
358
359    /// Count spending that is not a step, such as a compaction summary.
360    /// What the turn has spent so far.
361    pub fn cost(&self) -> f64 {
362        self.cost_usd
363    }
364
365    pub fn record_cost(&mut self, cost_usd: f64) {
366        self.cost_usd += cost_usd;
367    }
368
369    pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
370        if ok {
371            self.consecutive_errors = 0;
372            return Ok(());
373        }
374        self.consecutive_errors += 1;
375        if self.consecutive_errors > self.limits.max_consecutive_errors {
376            return Err(trip(format!(
377                "aborted after {} consecutive tool errors",
378                self.consecutive_errors
379            )));
380        }
381        Ok(())
382    }
383}
384
385fn trip(reason: String) -> HarnessError {
386    HarnessError::CircuitTripped(reason)
387}
388
389/// Everything one turn needs.
390pub struct Harness {
391    /// The session's model; the REPL's `/model` replaces it between turns. With
392    /// triage routing on, each turn may use another (see [`Harness::active_provider`]).
393    pub provider: Arc<dyn Provider>,
394    /// Triage routing (`crate::router`); [`Router::default`] never routes.
395    pub router: Router,
396    /// OpenTelemetry spans (`crate::otel`); [`crate::otel::Tracer::default`] records none.
397    pub tracer: crate::otel::Tracer,
398    pub registry: ToolRegistry,
399    pub context: ToolContext,
400    pub limits: LimitsConfig,
401    /// `[agents]`: whether `delegate` runs sub-agents, how deep, and how long.
402    pub agents: AgentsConfig,
403    pub system: Message,
404    /// The configured output cap, as Python's `max_output_tokens_for`; a session
405    /// override may replace it (see [`Harness::output_cap`]).
406    pub max_tokens: u32,
407    /// Limits overridden for the session, and the hook that offers to raise one
408    /// when a turn reaches it (`crate::limits`).
409    pub session_limits: crate::limits::SessionLimits,
410    /// Tokens of context the model can hold (`context_window_for`); the REPL's
411    /// `/model` updates it with the provider.
412    pub context_window: u64,
413    /// Decides whether side-effecting calls may run.
414    pub gate: ApprovalGate,
415    /// Ingress, egress, and observation scanning.
416    pub guardrails: Guardrails,
417    /// The flight recorder; [`Recorder::disabled`] writes nothing.
418    pub recorder: Recorder,
419    /// Live MCP servers; their section of the system message is rebuilt for every
420    /// request, because servers drop, reconnect, and change their tools mid-turn.
421    pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
422    /// Long-term memory: past episodes are recalled into each turn's system
423    /// message and every finished turn is recorded; `None` runs statelessly.
424    pub memory: Option<crate::session::SessionStore>,
425    /// Stops the running turn at its next safe point.
426    pub cancel: CancelToken,
427    /// Specialist sub-agents' state (beyond Python): notices for the user and the
428    /// approvals of project specialties (`crate::subagent`).
429    pub subagents: crate::subagent::SubagentState,
430    /// Reported against estimated input tokens, per model (beyond Python;
431    /// `crate::memory::sizing::Calibration`).
432    pub calibration: crate::memory::sizing::Calibration,
433    /// The verification gate (beyond Python; `crate::verify`): off by default.
434    pub verify: crate::verify::Verify,
435}
436
437impl Harness {
438    /// The system message for the next request: the prompt plus, when MCP servers
439    /// are live, their section, then the turn's recall note, as Python's
440    /// `_system_content`. Beyond Python, the names of the secrets the user entered
441    /// come before the recall note, when there are any.
442    pub(crate) fn system_message(&self, extra: Option<&str>) -> Message {
443        let offered = self.delegation_offered(&self.context, 0);
444        // Beyond Python: under `run --agent`, the specialty's filtered prompt.
445        if let Some((persona, preloaded, _)) = self.subagents.main() {
446            return self.filtered_system(&persona, &self.context, &preloaded, offered, extra);
447        }
448        self.system_for(&self.context, offered, extra)
449    }
450
451    /// [`Harness::system_message`] for `ctx`, an unrestricted context (the main
452    /// loop's, or a plain sub-agent's fork of it). Beyond Python, when `delegate`
453    /// is offered, the specialist sub-agents are listed after the MCP section.
454    pub(crate) fn system_for(
455        &self,
456        ctx: &ToolContext,
457        delegation_offered: bool,
458        extra: Option<&str>,
459    ) -> Message {
460        let mut system = self.system.clone();
461        if let Some(section) = self
462            .mcp
463            .as_ref()
464            .map(|mcp| mcp.prompt_section())
465            .filter(|section| !section.is_empty())
466        {
467            system.content = format!("{}\n\n{section}", system.content);
468        }
469        if delegation_offered {
470            if let Some(section) = self.specialty_listing(ctx) {
471                system.content = format!("{}\n\n{section}", system.content);
472            }
473        }
474        if let Some(section) = ctx.secrets.prompt_section() {
475            system.content = format!("{}\n\n{section}", system.content);
476        }
477        // Beyond Python (ADR 0006): how to ask the user, wherever someone can
478        // answer and the context may ask.
479        if crate::ask::reachable(ctx) && ctx.allowed_tool(crate::ask::ASK_USER) {
480            #[cfg(feature = "agent86ui")]
481            let drawing = ctx.ui.is_some() && ctx.allowed_tool(crate::agent86ui::RENDER_UI);
482            #[cfg(not(feature = "agent86ui"))]
483            let drawing = false;
484            system.content = format!(
485                "{}\n\n{}",
486                system.content,
487                crate::ask::prompt_section(drawing)
488            );
489        }
490        // Beyond Python: agent86UI's section, only where a renderer is and the
491        // context may draw.
492        #[cfg(feature = "agent86ui")]
493        if let Some(ui) = ctx.ui.as_deref() {
494            if ctx.allowed_tool(crate::agent86ui::RENDER_UI) {
495                system.content = format!("{}\n\n{}", system.content, ui.prompt_section());
496            }
497        }
498        if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
499            system.content = format!("{}\n\n{extra}", system.content);
500        }
501        system
502    }
503
504    /// Conversation tokens available for this request, as Python's
505    /// `_context_budget`: the window minus what the request spends before any
506    /// history (the system message and the tool catalogue, both of which change at
507    /// runtime), minus the room the response needs.
508    ///
509    /// Beyond Python, the budget shrinks for a model whose reported input tokens
510    /// have run above the estimate (`crate::memory::sizing::Calibration`).
511    pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
512        self.context_budget_with(
513            system,
514            specs,
515            self.active_context_window(),
516            self.output_cap(),
517            self.active_provider().model(),
518        )
519    }
520
521    /// A tool result cut to its share of `budget`, unless `[limits] context_sizing`
522    /// is off (`crate::memory::sizing::result_cap`).
523    pub(crate) fn cap_result(&self, content: String, budget: u64) -> String {
524        if !self.limits.context_sizing {
525            return content;
526        }
527        shorten_middle(
528            &content,
529            result_cap(budget, self.context.policy.max_output_chars),
530        )
531    }
532
533    /// `messages` as a request carries them: aged once the window fills, unless
534    /// `[limits] context_sizing` is off (`crate::memory::sizing::aged_view`).
535    pub(crate) fn request_view(
536        &self,
537        messages: &[Message],
538        budget: u64,
539    ) -> crate::memory::sizing::Aged {
540        if self.limits.context_sizing {
541            aged_view(messages, budget)
542        } else {
543            crate::memory::sizing::Aged {
544                messages: messages.to_vec(),
545                aged: 0,
546            }
547        }
548    }
549
550    /// [`Harness::context_budget`] for `model` with this window and output cap (a
551    /// sub-agent, perhaps on a model of its own). Beyond Python, with
552    /// `[limits] context_sizing` on, it is calibrated for the model
553    /// (`crate::memory::sizing::calibrated_budget`) and the reserve is held to a
554    /// share of the window (`sized_reserve`; the output cap already is).
555    pub(crate) fn context_budget_with(
556        &self,
557        system: &Message,
558        specs: &[ToolSpec],
559        window: u64,
560        output_cap: u32,
561        model: &str,
562    ) -> u64 {
563        let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
564        let (ratio, reserve) = if self.limits.context_sizing {
565            (
566                self.calibration.ratio(model),
567                sized_reserve(self.limits.context_reserve_tokens, window),
568            )
569        } else {
570            (1.0, self.limits.context_reserve_tokens)
571        };
572        calibrated_budget(
573            window,
574            overhead,
575            reserve,
576            u64::from(output_cap),
577            self.limits.max_context_tokens,
578            ratio,
579        )
580    }
581
582    /// The tools a main-loop request offers: the registry's, narrowed under
583    /// `run --agent` to what the specialty may call.
584    fn request_tools(&self) -> Vec<ToolSpec> {
585        let mut tools = self.registry.specs();
586        tools.retain(|spec| self.context.scope_allows(&spec.name));
587        tools
588    }
589
590    /// Write a summary of `messages` with the compaction summarizer (its prompt,
591    /// the cheap route when routing is on), as Python's summary call, with two
592    /// things beyond Python: the transcript is cut to fit the summarizer's own
593    /// window ([`fit_transcript`](crate::memory::working::fit_transcript)), and an
594    /// empty reply (a thinking model can spend the whole cap reasoning) is asked
595    /// for once more, with a larger cap and [`SUMMARY_RETRY_NOTE`]. The usage of
596    /// every attempt is returned, also on failure, since it was spent.
597    pub(crate) async fn write_summary(&self, messages: &[Message]) -> WrittenSummary {
598        let (summarizer, window) = self.summary_model();
599        let model = summarizer.model().to_owned();
600        let first_cap = SUMMARY_MAX_TOKENS * 2;
601        // Four times the first cap, but no more than a quarter of the window, so the
602        // retry still leaves the transcript room; never less than the first cap
603        // unless that is over half the window.
604        let share = |divisor: u64| u32::try_from(window / divisor).unwrap_or(u32::MAX);
605        let retry_cap = (SUMMARY_MAX_TOKENS * 8)
606            .min(share(4))
607            .max(first_cap.min(share(2)));
608        let instructions = message(Role::System, SUMMARY_SYSTEM_PROMPT);
609        let overhead = count_tokens(std::slice::from_ref(&instructions))
610            + count_tokens(&[message(Role::User, SUMMARY_RETRY_NOTE)])
611            + SUMMARY_MARGIN_TOKENS;
612        let room = window
613            .saturating_sub(overhead + u64::from(retry_cap))
614            .max(MIN_TRANSCRIPT_TOKENS);
615        let transcript =
616            summary_request_text(messages, usize::try_from(room * 4).unwrap_or(usize::MAX));
617        let mut usage = Usage::default();
618        let mut attempt = 0;
619        loop {
620            let (text, cap) = if attempt == 0 {
621                (transcript.clone(), first_cap)
622            } else {
623                (format!("{transcript}\n\n{SUMMARY_RETRY_NOTE}"), retry_cap)
624            };
625            let request = CompletionRequest {
626                model: model.clone(),
627                messages: vec![instructions.clone(), message(Role::User, &text)],
628                tools: Vec::new(),
629                temperature: 0.0,
630                // A summary is a bounded artefact; it should not cost more than the span.
631                max_tokens: Some(cap),
632                stream: false,
633            };
634            let completion = tokio::select! {
635                biased;
636                // The next safe point sees the cancel and closes the turn out.
637                () = self.cancel.cancelled() => {
638                    return WrittenSummary { outcome: Err(SummaryError::Cancelled), usage, model };
639                }
640                completion = summarizer.complete(request) => completion,
641            };
642            let completion = match completion {
643                Ok(completion) => completion,
644                Err(error) => {
645                    return WrittenSummary {
646                        outcome: Err(SummaryError::Failed(format!("ProviderError: {error}"))),
647                        usage,
648                        model,
649                    }
650                }
651            };
652            usage = usage + completion.usage;
653            let text = python_strip(&completion.text).to_owned();
654            if !text.is_empty() {
655                return WrittenSummary {
656                    outcome: Ok(text),
657                    usage,
658                    model,
659                };
660            }
661            if attempt > 0 {
662                return WrittenSummary {
663                    outcome: Err(SummaryError::Empty),
664                    usage,
665                    model,
666                };
667            }
668            attempt += 1;
669        }
670    }
671
672    /// Replace the oldest over-budget span with a summary, in place, before a model
673    /// call, as Python's `_compact_if_needed`. Dropping the oldest turns (still
674    /// available as `compaction = "drop"`) makes a long session forget its own
675    /// goal; a summary keeps the goal, the decisions, and the paths found.
676    ///
677    /// Beyond Python, the span may reach inside the current turn
678    /// ([`compaction_plan`]): the turn's message is kept verbatim with the summary
679    /// appended, so a long single turn compacts too instead of losing its goal to
680    /// fitting. A failed or empty summary is not tried again until the history has
681    /// grown by a quarter of the budget, so a summarizer that cannot answer is not
682    /// asked every step.
683    ///
684    /// Never fails the turn: a summary that cannot be written falls back to the drop
685    /// that fitting the request does anyway, and says so.
686    async fn compact_if_needed(
687        &self,
688        state: &mut AgentState,
689        extra_system: Option<&str>,
690        summary: &mut TurnSummary,
691        breaker: &mut CircuitBreaker,
692        window: &mut TurnWindow<'_>,
693    ) -> Option<Compaction> {
694        if self.limits.compaction != CompactionMode::Summarize {
695            return None;
696        }
697        let system = self.system_message(extra_system);
698        let budget = self.context_budget(&system, &self.request_tools());
699        // Beyond Python: judged on what a request would carry, so a history that
700        // fits once its older results are aged costs no summary.
701        if fits(&self.request_view(&state.messages, budget).messages, budget) {
702            return None;
703        }
704        let tokens = count_tokens(&state.messages);
705        if window.retry_at.is_some_and(|at| tokens < at) {
706            return None;
707        }
708        // Everything left is recent or the current turn's own message and tool
709        // blocks: nothing may be compacted, so fitting trims and the provider's
710        // limits take over.
711        let cut = compaction_plan(
712            &state.messages,
713            budget,
714            KEEP_RECENT,
715            window.goal,
716            window.continuation,
717        )?;
718        let sid = state.session_id.clone();
719        let end = cut.cut();
720        let replaced = cut.replaced();
721        let prefix = &state.messages[..end];
722        let dropped_tokens = count_tokens(prefix);
723        let written = self.write_summary(prefix).await;
724        summary.add_usage(&written.usage);
725        breaker.record_cost(written.usage.cost_usd);
726        let failed = |window: &mut TurnWindow<'_>, status: &str, error: Option<String>| {
727            window.retry_at = Some(tokens + (budget / 4).max(1));
728            let mut fields = vec![
729                ("status", json!(status)),
730                ("fallback", json!("drop")),
731                ("dropped", json!(replaced)),
732            ];
733            if let Some(error) = error {
734                fields.push(("error", json!(error)));
735            }
736            self.recorder.event(&sid, "compaction", fields);
737            Some(Compaction {
738                notice: compaction_failed_notice(replaced),
739                summary: None,
740            })
741        };
742        let text = match written.outcome {
743            Ok(text) => text,
744            Err(SummaryError::Cancelled) => return None,
745            Err(SummaryError::Failed(error)) => return failed(window, "failed", Some(error)),
746            Err(SummaryError::Empty) => return failed(window, "empty", None),
747        };
748        window.retry_at = None;
749
750        // The originals are archived before they leave the live conversation.
751        if let Some(memory) = &self.memory {
752            let _ = memory.record_compaction(&sid, &text, prefix);
753        }
754        let before = state.messages.len();
755        let kept = state.messages.split_off(end);
756        state.messages = match cut {
757            Cut::Earlier(_) => apply_summary(&text, kept),
758            Cut::WithinTurn { .. } => apply_progress(window.goal_text, &text, kept),
759        };
760        let removed = before - state.messages.len();
761        // Indices into the history move with it. (Python keeps the old ones, which
762        // go stale after a compaction mid-turn.)
763        window.goal = match cut {
764            Cut::Earlier(_) => window.goal - removed,
765            Cut::WithinTurn { .. } => 0,
766        };
767        if let Some(start) = window.continuation.as_mut() {
768            *start -= removed;
769        }
770        summary.compactions += 1;
771        let mut fields = vec![
772            ("status", json!("ok")),
773            ("dropped", json!(replaced)),
774            ("dropped_tokens", json!(dropped_tokens)),
775            (
776                "summary_tokens",
777                json!(count_tokens(&[message(Role::User, &text)])),
778            ),
779            ("kept", json!(state.messages.len())),
780            ("model", json!(written.model)),
781        ];
782        if matches!(cut, Cut::WithinTurn { .. }) {
783            fields.push(("scope", json!("turn")));
784        }
785        self.recorder.event(&sid, "compaction", fields);
786        // Saved at once: a resume must see the compacted history, not a stale copy
787        // that would re-inflate the context on the next turn.
788        if let Some(memory) = &self.memory {
789            let _ = memory.persist(state);
790        }
791        Some(Compaction {
792            notice: compacted_notice(replaced),
793            summary: Some(text),
794        })
795    }
796
797    /// Run one user turn on `state`, passing every piece of streamed text,
798    /// including tool notices, to `on_text`, and return everything streamed.
799    ///
800    /// The turn's messages and steps are appended to `state`, its usage added,
801    /// and its summary left on `state.last_turn`. A failed turn still leaves
802    /// `state` in the `error` phase with its summary, so it can be persisted.
803    pub async fn run_turn(
804        &self,
805        state: &mut AgentState,
806        goal: &str,
807        on_text: impl FnMut(&str),
808    ) -> Result<String, HarnessError> {
809        self.run_turn_as(state, goal, goal, on_text).await
810    }
811
812    /// [`Harness::run_turn`] where the model sees `user_text` (for a prompt with
813    /// `@file` mentions, the expanded text) and the trace records `display_text`,
814    /// what the user typed, as Python's `display_text` argument.
815    pub async fn run_turn_as(
816        &self,
817        state: &mut AgentState,
818        user_text: &str,
819        display_text: &str,
820        mut on_text: impl FnMut(&str),
821    ) -> Result<String, HarnessError> {
822        self.run_turn_events(state, user_text, display_text, |event| {
823            on_text(event.text())
824        })
825        .await
826    }
827
828    /// [`Harness::run_turn_as`] reporting [`TurnEvent`]s, so an interface can show
829    /// tool calls without parsing the `[tool] ...` lines. Every event carries the text
830    /// the other entry points stream, in the same order.
831    pub async fn run_turn_events(
832        &self,
833        state: &mut AgentState,
834        user_text: &str,
835        display_text: &str,
836        on_event: impl FnMut(TurnEvent<'_>),
837    ) -> Result<String, HarnessError> {
838        self.run_turn_with(state, user_text, display_text, None, on_event)
839            .await
840    }
841
842    /// A turn with `skill` chosen by the user (`/<name> [task]`, `/skill <name>`,
843    /// `run --skill`), beyond Python: the model gets the skill's instructions ahead
844    /// of `task` in the user's message ([`crate::skills::skill_request`]), and the
845    /// skill is active from the first step, so its `allowed-tools` apply at once.
846    /// Everything else is [`Harness::run_turn_events`]; `display_text` is what the
847    /// user typed, for the trace.
848    pub async fn run_skill_turn(
849        &self,
850        state: &mut AgentState,
851        skill: &Arc<crate::skills::Skill>,
852        task: &str,
853        display_text: &str,
854        on_event: impl FnMut(TurnEvent<'_>),
855    ) -> Result<String, HarnessError> {
856        let user_text = crate::skills::skill_request(skill, task);
857        self.run_turn_with(state, &user_text, display_text, Some(skill), on_event)
858            .await
859    }
860
861    async fn run_turn_with(
862        &self,
863        state: &mut AgentState,
864        user_text: &str,
865        display_text: &str,
866        skill: Option<&Arc<crate::skills::Skill>>,
867        on_event: impl FnMut(TurnEvent<'_>),
868    ) -> Result<String, HarnessError> {
869        // A cancel requested while no turn was running must not kill this one.
870        self.cancel.clear();
871        // A skill activated with `use_skill` restricts tools for its turn only: the
872        // restriction is lifted on entry and on every exit, so it can never keep
873        // refusing tools for the rest of the session. A skill the user ran is then
874        // made active for this turn alone.
875        self.context.clear_skill();
876        if let Some(skill) = skill {
877            self.context.activate_skill(skill);
878        }
879        let started = Instant::now();
880        // One `turn` span per user turn, parent of its model and tool spans.
881        let mut span = self.tracer.start(
882            "turn",
883            vec![
884                ("session.id", json!(state.session_id)),
885                (
886                    "gen_ai.request.model",
887                    json!(self.active_provider().model()),
888                ),
889            ],
890        );
891        let mut summary = TurnSummary::default();
892        // A secret the user pasted anyway (or an `@file` that holds one) goes no
893        // further than this: not to the model, the history, nor the trace.
894        let secrets = &self.context.secrets;
895        let (user_text, display_text) = (secrets.redact(user_text), secrets.redact(display_text));
896        let result = self
897            .turn(state, &user_text, &display_text, &mut summary, on_event)
898            .await;
899        self.context.clear_skill();
900        summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
901        state.last_turn = Some(summary);
902        if let Err(error) = &result {
903            state.phase = AgentPhase::Error;
904            let reason = match error {
905                HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
906                HarnessError::Provider(detail) => {
907                    format!("provider stream failed: ProviderError: {detail}")
908                }
909                HarnessError::NoFinalCompletion { .. } => {
910                    "provider stream ended without a final completion".to_owned()
911                }
912            };
913            self.recorder.event(
914                &state.session_id,
915                "turn_end",
916                vec![("status", json!("error")), ("reason", json!(reason))],
917            );
918        }
919        // Closed with what the turn spent, on every exit, so a backend sees the cost
920        // of an aborted turn too.
921        span.set(turn_attributes(state, self.active_provider().model()));
922        if let Err(error) = &result {
923            span.fail(error.python_type(), &error.to_string());
924        }
925        self.tracer.end(span);
926        result
927    }
928
929    async fn turn(
930        &self,
931        state: &mut AgentState,
932        goal: &str,
933        display_text: &str,
934        summary: &mut TurnSummary,
935        mut on_event: impl FnMut(TurnEvent<'_>),
936    ) -> Result<String, HarnessError> {
937        let mut output = String::new();
938        let mut emit = |event: TurnEvent<'_>| {
939            output.push_str(event.text());
940            on_event(event);
941        };
942
943        let sid = state.session_id.clone();
944        self.recorder
945            .event(&sid, "turn_start", vec![("task", json!(display_text))]);
946        self.verify.set_last(None);
947
948        // Ingress guardrail on the user's input.
949        let report = self.guardrails.inspect_ingress(goal);
950        if report.flagged() {
951            self.recorder.event(
952                &sid,
953                "guardrail",
954                vec![
955                    ("stage", json!("ingress_input")),
956                    ("findings", json!(report.summary())),
957                ],
958            );
959            if self.guardrails.should_block(&report) {
960                let refusal = format!(
961                    "Refused: input tripped the ingress guardrail ({}).",
962                    report.summary()
963                );
964                state.messages.push(message(Role::User, goal));
965                state.messages.push(message(Role::Assistant, &refusal));
966                state.phase = AgentPhase::Error;
967                self.recorder
968                    .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
969                emit(TurnEvent::Text(&refusal));
970                return Ok(output);
971            }
972            emit(TurnEvent::Notice(&format!(
973                "[guardrail] input flagged: {}\n",
974                report.summary()
975            )));
976        }
977
978        // Redact mode cannot stream: text inspected only after it was shown has
979        // already leaked. Each step's text is held back and replayed redacted.
980        let buffering = self.guardrails.egress == EgressMode::Redact;
981
982        // Pick this turn's model (triage routing), after the input was let through.
983        self.route(goal, &sid)?;
984        let provider = self.active_provider();
985
986        // What happened last time a task like this came up.
987        let recall_note = self
988            .memory
989            .as_ref()
990            .and_then(|memory| memory.recall_note(goal));
991        // Beyond Python: the time the turn started, then what was recalled.
992        let time = time_note(&jiff::ZonedDateTime::now());
993        let recall_note = Some(match recall_note {
994            Some(recalled) => format!("{time}\n\n{recalled}"),
995            None => time,
996        });
997        // Where this turn begins. Its message is never summarized away nor left out
998        // of a request (beyond Python, whose fitting drops it first in a long turn);
999        // compaction may reach past it, keeping it verbatim.
1000        let mut window = TurnWindow {
1001            goal_text: goal,
1002            goal: state.messages.len(),
1003            continuation: None,
1004            retry_at: None,
1005            trim_announced: false,
1006            trimmed: 0,
1007            aged: 0,
1008        };
1009        state.messages.push(message(Role::User, goal));
1010        let mut limits = self.limits.clone();
1011        limits.max_steps = self.max_steps();
1012        let mut breaker = CircuitBreaker::new(&limits);
1013        let mut broken_streak = BrokenStreak::default();
1014        // Where the first partial answer went, and the pieces collected so far.
1015        let mut continuation_start: Option<usize> = None;
1016        let mut continuation_parts: Vec<String> = Vec::new();
1017        // Beyond Python: an empty final reply is asked about once (`ask_again` puts
1018        // ANSWER_PROMPT on the next request only, never in the history), and the
1019        // reasoning it came with is kept in case the second try is empty too.
1020        let mut nudged = false;
1021        let mut ask_again = false;
1022        let mut unanswered_thinking = String::new();
1023        // Beyond Python: the verification gate's progress (`crate::verify`).
1024        let mut verify_run = crate::verify::VerifyRun::default();
1025        // Beyond Python: one reminder per way of going in circles (`crate::stall`).
1026        let mut stall = crate::stall::StallWatch::new(self.limits.stall_nudge);
1027
1028        loop {
1029            // Never start another model call once cancelled: that is the expensive,
1030            // long-latency step the user is trying to escape.
1031            if self.cancel.is_cancelled() {
1032                self.cancelled(state, breaker.steps(), &mut emit);
1033                return Ok(output);
1034            }
1035            // Beyond Python: the interface may offer to raise a spent budget.
1036            if breaker.out_of_steps() {
1037                match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
1038                    Some(raised) => breaker.set_max_steps(raised),
1039                    // Ctrl+C at the offer stops it and cancels the turn.
1040                    None if self.cancel.is_cancelled() => {
1041                        self.cancelled(state, breaker.steps(), &mut emit);
1042                        return Ok(output);
1043                    }
1044                    None => {}
1045                }
1046            }
1047            breaker.before_step()?;
1048
1049            // Compact before the request is built, so the model call sees the
1050            // compacted history. Once per step, never nested.
1051            window.continuation = continuation_start;
1052            if let Some(compaction) = self
1053                .compact_if_needed(
1054                    state,
1055                    recall_note.as_deref(),
1056                    summary,
1057                    &mut breaker,
1058                    &mut window,
1059                )
1060                .await
1061            {
1062                continuation_start = window.continuation;
1063                // A failed summary says what fitting drops; a written one starts
1064                // the count again.
1065                window.trim_announced = compaction.summary.is_none();
1066                // Said out loud: a conversation that quietly lost its oldest turns
1067                // looks, from the user's seat, like a model that forgot.
1068                emit(TurnEvent::Compacted {
1069                    notice: &compaction.notice,
1070                    summary: compaction.summary.as_deref(),
1071                });
1072            }
1073
1074            // The request's estimated size, for calibration, and the budget the
1075            // step's results are capped against.
1076            let estimated;
1077            let step_budget;
1078            let mut completion = {
1079                let system = self.system_message(recall_note.as_deref());
1080                // Under `run --agent`, only what the specialty may call is offered.
1081                let tools = self.request_tools();
1082                let budget = self.context_budget(&system, &tools);
1083                step_budget = budget;
1084                // Beyond Python: older results go as stubs once the window fills.
1085                let aged = self.request_view(&state.messages, budget);
1086                self.announce_age(&sid, aged.aged, budget, &mut window);
1087                let fitted = fit_pinned(&aged.messages, budget, Some(window.goal));
1088                self.announce_trim(&sid, &fitted, budget, &mut window, &mut emit);
1089                let mut request_messages = Vec::with_capacity(fitted.messages.len() + 1);
1090                request_messages.push(system);
1091                request_messages.extend(fitted.messages);
1092                if std::mem::take(&mut ask_again) {
1093                    request_messages.push(message(Role::User, ANSWER_PROMPT));
1094                }
1095                estimated = count_tokens(&request_messages) + count_spec_tokens(&tools);
1096                let request = CompletionRequest {
1097                    model: provider.model().to_owned(),
1098                    messages: request_messages,
1099                    tools,
1100                    // Beyond Python: `run --agent`'s specialty, else the section's.
1101                    temperature: request_temperature(
1102                        provider.as_ref(),
1103                        self.subagents.main().and_then(|main| main.2),
1104                    ),
1105                    max_tokens: Some(self.output_cap()),
1106                    stream: true,
1107                };
1108                // GenAI semantic conventions where a name exists, `agent86.*` otherwise.
1109                let mut span = self.tracer.start(
1110                    "model_call",
1111                    vec![
1112                        ("gen_ai.system", json!(provider.name())),
1113                        ("gen_ai.request.model", json!(provider.model())),
1114                        ("agent86.step", json!(breaker.steps() + 1)),
1115                    ],
1116                );
1117                let mut stream = provider.stream(request);
1118                let mut completion = None;
1119                let mut buffered = String::new();
1120                // The model never saw a secret's value, but should it produce one
1121                // anyway, it is not shown.
1122                let mut redactor = StreamRedactor::default();
1123                let mut thinking_redactor = StreamRedactor::default();
1124                loop {
1125                    // A long or stalled response stops mid-flight, not after it ends.
1126                    // Dropping the stream drops the HTTP response.
1127                    let next = tokio::select! {
1128                        biased;
1129                        () = self.cancel.cancelled() => None,
1130                        delta = stream.next() => Some(delta),
1131                    };
1132                    let Some(Some(delta)) = next else { break };
1133                    let delta = match delta {
1134                        Ok(delta) => delta,
1135                        Err(error) => {
1136                            span.set(model_call_attributes(None));
1137                            span.fail("ProviderError", &error.to_string());
1138                            self.tracer.end(span);
1139                            return Err(error.into());
1140                        }
1141                    };
1142                    // Reasoning is shown only as it streams. Redact mode holds text
1143                    // back until the guardrail has seen it, so it shows none.
1144                    if !delta.thinking.is_empty() && !buffering {
1145                        let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
1146                        if !shown.is_empty() {
1147                            emit(TurnEvent::Thinking(&shown));
1148                        }
1149                    }
1150                    if !delta.text.is_empty() {
1151                        if buffering {
1152                            buffered.push_str(&delta.text);
1153                        } else {
1154                            let shown = redactor.push(&self.context.secrets, &delta.text);
1155                            if !shown.is_empty() {
1156                                emit(TurnEvent::Text(&shown));
1157                            }
1158                        }
1159                    }
1160                    if delta.done && delta.completion.is_some() {
1161                        completion = delta.completion;
1162                    }
1163                }
1164                drop(stream);
1165                let held = thinking_redactor.finish(&self.context.secrets);
1166                if !held.is_empty() {
1167                    emit(TurnEvent::Thinking(&held));
1168                }
1169                let held = redactor.finish(&self.context.secrets);
1170                if !held.is_empty() {
1171                    emit(TurnEvent::Text(&held));
1172                }
1173                span.set(model_call_attributes(completion.as_ref()));
1174                self.tracer.end(span);
1175                if self.cancel.is_cancelled() {
1176                    // Whatever was held back still belongs to the user: redacted, then shown.
1177                    let partial = self
1178                        .guardrails
1179                        .inspect_egress(&self.context.secrets.redact(&buffered))
1180                        .1;
1181                    if !partial.is_empty() {
1182                        emit(TurnEvent::Text(&partial));
1183                    }
1184                    self.cancelled(state, breaker.steps(), &mut emit);
1185                    return Ok(output);
1186                }
1187                completion.ok_or_else(|| HarnessError::NoFinalCompletion {
1188                    provider: provider.name().to_owned(),
1189                    model: provider.model().to_owned(),
1190                })?
1191            };
1192
1193            breaker.record_step(&completion.usage);
1194            if self.limits.context_sizing {
1195                self.calibration.observe(
1196                    provider.model(),
1197                    estimated,
1198                    completion.usage.input_tokens,
1199                );
1200            }
1201            summary.steps = u64::from(breaker.steps());
1202            summary.add_usage(&completion.usage);
1203            // Beyond Python: what this call used, and the session so far, for a
1204            // surface that shows it as it goes (an editor's `usage_update`).
1205            emit(TurnEvent::Usage {
1206                step: &completion.usage,
1207                session: &(state.usage + completion.usage),
1208            });
1209            let names: Vec<&str> = completion
1210                .tool_calls
1211                .iter()
1212                .map(|call| call.name.as_str())
1213                .collect();
1214            self.recorder.event(
1215                &sid,
1216                "model_call",
1217                vec![
1218                    ("step", json!(breaker.steps())),
1219                    ("model", json!(provider.model())),
1220                    ("input_tokens", json!(completion.usage.input_tokens)),
1221                    ("output_tokens", json!(completion.usage.output_tokens)),
1222                    ("cost_usd", json!(completion.usage.cost_usd)),
1223                    ("stop_reason", json!(completion.stop_reason)),
1224                    ("tool_calls", json!(names)),
1225                ],
1226            );
1227
1228            if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
1229                emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
1230            }
1231            // Beyond Python: the provider ended the reply itself (Gemini's SAFETY,
1232            // RECITATION, ...; an OpenAI-compatible content filter; a model's
1233            // refusal). Said once, and not asked about again.
1234            let stopped = completion
1235                .stop_reason
1236                .as_deref()
1237                .and_then(|reason| reason.strip_prefix(crate::provider::STOPPED_PREFIX))
1238                .map(str::to_owned);
1239            if let Some(reason) = &stopped {
1240                emit(TurnEvent::Notice(&format!(
1241                    "\n[{} stopped the reply: {reason}]\n",
1242                    provider.name()
1243                )));
1244            }
1245
1246            // Beyond Python: a reply that ends cleanly with nothing to say (a thinking
1247            // model can put its whole answer in its reasoning) is asked about once.
1248            // The empty step stays out of the history. If the second reply is empty
1249            // too, the reasoning stands in for the answer. A reply cut off at the cap
1250            // is the continuation path's, and a model out of steps is not asked again.
1251            let mut from_thinking = false;
1252            if completion.tool_calls.is_empty()
1253                && completion.stop_reason.as_deref() != Some("max_tokens")
1254                && stopped.is_none()
1255                && completion.text.trim().is_empty()
1256                && continuation_start.is_none()
1257            {
1258                if !completion.thinking.trim().is_empty() {
1259                    unanswered_thinking = std::mem::take(&mut completion.thinking);
1260                }
1261                if !nudged && !breaker.out_of_steps() {
1262                    nudged = true;
1263                    ask_again = true;
1264                    self.recorder.event(
1265                        &sid,
1266                        "empty_answer",
1267                        vec![
1268                            ("step", json!(breaker.steps())),
1269                            ("model", json!(provider.model())),
1270                            ("thinking_chars", json!(unanswered_thinking.chars().count())),
1271                        ],
1272                    );
1273                    record_step(
1274                        state,
1275                        Step {
1276                            index: state.steps.len() as u64 + 1,
1277                            phase: AgentPhase::Execute,
1278                            thought: String::new(),
1279                            tool_calls: Vec::new(),
1280                            results: Vec::new(),
1281                            usage: completion.usage,
1282                        },
1283                    );
1284                    self.checkpoint(state);
1285                    emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1286                    continue;
1287                }
1288                if unanswered_thinking.trim().is_empty() {
1289                    emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1290                    // Beyond Python: LM Studio has been seen to answer a request that
1291                    // overflows the loaded context with nothing at all.
1292                    if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1293                        emit(TurnEvent::Notice(&format!(
1294                            "{}\n",
1295                            crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1296                        )));
1297                    }
1298                } else {
1299                    completion.text = std::mem::take(&mut unanswered_thinking);
1300                    from_thinking = true;
1301                    emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1302                }
1303            }
1304
1305            // Egress guardrail on the model's text. In redact mode the redacted copy
1306            // is what everything downstream sees: the output, the history, and the step.
1307            let answer = self.context.secrets.redact(&completion.text);
1308            let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1309            let text = if buffering {
1310                if !redacted.is_empty() {
1311                    emit(TurnEvent::Text(&redacted));
1312                }
1313                redacted
1314            } else {
1315                // Reasoning standing in for the answer was never streamed as text.
1316                if from_thinking {
1317                    emit(TurnEvent::Text(&answer));
1318                }
1319                answer
1320            };
1321            if egress.flagged() {
1322                self.recorder.event(
1323                    &sid,
1324                    "guardrail",
1325                    vec![
1326                        ("stage", json!("egress")),
1327                        ("findings", json!(egress.summary())),
1328                    ],
1329                );
1330                emit(TurnEvent::Notice(&format!(
1331                    "\n[guardrail] output flagged: {}\n",
1332                    egress.summary()
1333                )));
1334            }
1335            let mut tool_calls = completion.tool_calls;
1336            // Before anything keeps or sees the calls, so all see the repair.
1337            let repairs = self.repair_broken_calls(&mut tool_calls, &sid);
1338            self.scan_tool_arguments(&tool_calls, &sid);
1339            let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1340            // Beyond Python: a reply that reached the cap before writing anything (a
1341            // thinking model can spend all of it reasoning) has nothing to continue
1342            // from. The interface may offer a larger cap and ask again; the empty
1343            // reply is kept out of the history.
1344            if cut_off
1345                && tool_calls.is_empty()
1346                && text.trim().is_empty()
1347                && continuation_start.is_none()
1348            {
1349                let cap = self.output_cap();
1350                if self
1351                    .raise_limit(LimitKind::Output, None, &sid, cap, false)
1352                    .is_some()
1353                {
1354                    record_step(
1355                        state,
1356                        Step {
1357                            index: state.steps.len() as u64 + 1,
1358                            phase: AgentPhase::Execute,
1359                            thought: String::new(),
1360                            tool_calls: Vec::new(),
1361                            results: Vec::new(),
1362                            usage: completion.usage,
1363                        },
1364                    );
1365                    self.checkpoint(state);
1366                    continue;
1367                }
1368            }
1369            let mut step = Step {
1370                index: state.steps.len() as u64 + 1,
1371                phase: AgentPhase::Execute,
1372                thought: text.clone(),
1373                tool_calls: tool_calls.clone(),
1374                results: Vec::new(),
1375                usage: completion.usage,
1376            };
1377            state.messages.push(Message {
1378                tool_calls: tool_calls.clone(),
1379                ..message(Role::Assistant, &text)
1380            });
1381
1382            if tool_calls.is_empty() {
1383                if cut_off && summary.continuations < MAX_CONTINUATIONS {
1384                    summary.continuations += 1;
1385                    continuation_start.get_or_insert(state.messages.len() - 1);
1386                    continuation_parts.push(text);
1387                    state.messages.push(message(Role::User, CONTINUE_PROMPT));
1388                    record_step(state, step);
1389                    self.checkpoint(state);
1390                    self.recorder.event(
1391                        &sid,
1392                        "continuation",
1393                        vec![
1394                            ("index", json!(summary.continuations)),
1395                            ("step", json!(breaker.steps())),
1396                            ("model", json!(provider.model())),
1397                            (
1398                                "chars",
1399                                json!(continuation_parts
1400                                    .last()
1401                                    .map_or(0, |part| part.chars().count())),
1402                            ),
1403                        ],
1404                    );
1405                    emit(TurnEvent::Notice(&continuation_notice(
1406                        summary.continuations,
1407                    )));
1408                    continue;
1409                }
1410                if let Some(start) = continuation_start.take() {
1411                    // Collapse [partial, "continue", partial, ...] into one answer.
1412                    continuation_parts.push(text);
1413                    let joined = std::mem::take(&mut continuation_parts).concat();
1414                    state.messages.truncate(start);
1415                    state.messages.push(message(Role::Assistant, &joined));
1416                    step.thought = joined;
1417                }
1418                // Beyond Python: with `[verify] command` set, a turn that changed the
1419                // workspace ends only once the check passes or its attempts run out.
1420                let steps_left = !breaker.out_of_steps();
1421                if let crate::verify::Gate::SendBack(feedback) =
1422                    self.verify_answer(&mut verify_run, steps_left, &sid, &mut emit)
1423                {
1424                    record_step(state, step);
1425                    state.messages.push(message(Role::User, &feedback));
1426                    self.checkpoint(state);
1427                    continue;
1428                }
1429                let outcome = step.thought.clone();
1430                record_step(state, step);
1431                state.phase = AgentPhase::Done;
1432                self.recorder.event(
1433                    &sid,
1434                    "turn_end",
1435                    vec![
1436                        ("status", json!("done")),
1437                        ("steps", json!(breaker.steps())),
1438                        ("continuations", json!(summary.continuations)),
1439                    ],
1440                );
1441                if let Some(memory) = &self.memory {
1442                    // A failed write loses one episode, never the turn.
1443                    let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1444                }
1445                return Ok(output);
1446            }
1447
1448            // A step that wants tools ends any continuation in progress.
1449            continuation_start = None;
1450            continuation_parts.clear();
1451
1452            // Before the batch, never mid-execution. Python leaves these calls
1453            // unanswered, which providers reject on the next request; each is
1454            // answered here as not executed, as a cancel mid-batch does.
1455            if self.cancel.is_cancelled() {
1456                for call in &tool_calls {
1457                    let result = not_executed(call, "cancelled");
1458                    state.messages.push(Message {
1459                        tool_call_id: Some(call.id.clone()),
1460                        name: Some(call.name.clone()),
1461                        ..message(Role::Tool, &observation(&result))
1462                    });
1463                    step.results.push(result);
1464                }
1465                record_step(state, step);
1466                self.cancelled(state, breaker.steps(), &mut emit);
1467                return Ok(output);
1468            }
1469
1470            // The whole batch is announced up front, then observed strictly in call order.
1471            for call in &tool_calls {
1472                let text = format!(
1473                    "\n[tool] {}({})\n",
1474                    call.name,
1475                    preview_arguments(&call.arguments)
1476                );
1477                emit(TurnEvent::ToolCall { call, text: &text });
1478            }
1479            let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1480            // Beyond Python: what a sub-agent had to tell the user (a specialty's
1481            // model that could not be built), as notices, so `run`'s stdout keeps
1482            // only the answer.
1483            for notice in self.take_notices() {
1484                emit(TurnEvent::Notice(&format!("{notice}\n")));
1485            }
1486            // Questions shown as text (ADR 0006's text fallback), which end the turn.
1487            let mut asked_in_text: Option<String> = None;
1488            for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1489                summary.tool_calls += 1;
1490                // What render_ui drew goes to the surface, never to the session or
1491                // the trace (the call's arguments already hold it).
1492                #[cfg(feature = "agent86ui")]
1493                let result = {
1494                    let mut result = result;
1495                    let (drawn, trace) = crate::agent86ui::take_drawn(&mut result.metadata);
1496                    for message in &drawn {
1497                        emit(TurnEvent::Ui(message));
1498                    }
1499                    if let Some(Value::Object(fields)) = trace {
1500                        // agent86's own kind (Python has none): which surfaces, how
1501                        // many components, and the verdict, never the tree.
1502                        let fields: Vec<(&str, Value)> = fields
1503                            .iter()
1504                            .map(|(key, value)| (key.as_str(), value.clone()))
1505                            .collect();
1506                        self.recorder.event(&sid, "ui_render", fields);
1507                    }
1508                    // A waiting call asks now that its messages are out, so the
1509                    // program has them to draw before it is asked for an answer.
1510                    match crate::agent86ui::take_wait(&mut result.metadata) {
1511                        Some(surfaces) => self.ui_wait(call, result, surfaces, &sid),
1512                        None => result,
1513                    }
1514                };
1515                // An `ask_user` call asks now (ADR 0006), after anything drawn
1516                // before it in the batch is out.
1517                let mut result = self.ask_questions(call, result, &sid, &mut emit);
1518                if let Some(Value::String(text)) = result.metadata.remove(crate::ask::ASK_TEXT_KEY)
1519                {
1520                    asked_in_text = Some(match asked_in_text.take() {
1521                        Some(earlier) => format!("{earlier}\n\n{text}"),
1522                        None => text,
1523                    });
1524                }
1525                let result = self.annotate_broken_json(call, result, &repairs, &mut broken_streak);
1526                // What a sub-agent spent is what this turn spent: in the summary, the
1527                // step, and the cost cap, but not as one of this turn's steps.
1528                summary.add_usage(&delegated);
1529                step.usage = step.usage + delegated;
1530                breaker.record_cost(delegated.cost_usd);
1531                let (content, findings) = self.guardrails.observe(observation(&result));
1532                // Beyond Python: no result takes more than its share of the window.
1533                let content = self.cap_result(content, step_budget);
1534                if let Some(findings) = findings {
1535                    self.recorder.event(
1536                        &sid,
1537                        "guardrail",
1538                        vec![
1539                            ("stage", json!("observation")),
1540                            ("tool", json!(call.name)),
1541                            ("findings", json!(findings)),
1542                        ],
1543                    );
1544                }
1545                emit(TurnEvent::ToolResult {
1546                    call,
1547                    result: &result,
1548                    observation: &content,
1549                    text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1550                });
1551                state.messages.push(Message {
1552                    tool_call_id: Some(call.id.clone()),
1553                    name: Some(call.name.clone()),
1554                    ..message(Role::Tool, &content)
1555                });
1556                let ok = result.ok;
1557                verify_run.saw(&call.name, ok);
1558                stall.saw(call, &result, &content);
1559                step.results.push(result);
1560                if let Err(tripped) = breaker.record_tool_result(ok) {
1561                    record_step(state, step);
1562                    return Err(tripped);
1563                }
1564            }
1565            // ADR 0006's text fallback: the questions are the agent's message, kept
1566            // as an ordinary assistant message after the results (so the history
1567            // alternates as every provider requires, and reads naturally on resume
1568            // and in Python), and the turn ends without another model call. No new
1569            // stop reason is stored; the user's reply is the next turn.
1570            if let Some(questions) = asked_in_text {
1571                emit(TurnEvent::Text(&questions));
1572                state.messages.push(message(Role::Assistant, &questions));
1573                record_step(state, step);
1574                state.phase = AgentPhase::Done;
1575                self.recorder.event(
1576                    &sid,
1577                    "turn_end",
1578                    vec![
1579                        ("status", json!("done")),
1580                        ("steps", json!(breaker.steps())),
1581                        ("continuations", json!(summary.continuations)),
1582                    ],
1583                );
1584                if let Some(memory) = &self.memory {
1585                    let _ = memory.add_episode(&sid, goal, &questions, &Default::default());
1586                }
1587                return Ok(output);
1588            }
1589            // Every call has an observation by now, including any skipped because
1590            // the cancel landed mid-batch, so a note can follow them.
1591            if let Some(found) = stall.take() {
1592                self.remind_of_stall(&found, &sid, &mut emit);
1593                state.messages.push(message(Role::User, &found.note()));
1594            }
1595            record_step(state, step);
1596            self.checkpoint(state);
1597            if self.cancel.is_cancelled() {
1598                self.cancelled(state, breaker.steps(), &mut emit);
1599                return Ok(output);
1600            }
1601        }
1602    }
1603
1604    /// Save the session at a step boundary (beyond Python; checkpointing tier 1,
1605    /// `docs/checkpointing.md`), so a process that dies mid-turn keeps the steps it
1606    /// finished. Only called once every tool call in the history has its answer.
1607    /// The phase reads `execute` until the turn ends, when every exit sets `done`
1608    /// or `error`, so a saved state that still says `execute` is a turn cut off.
1609    /// A failed write loses one checkpoint, never the turn.
1610    fn checkpoint(&self, state: &mut AgentState) {
1611        state.phase = AgentPhase::Execute;
1612        if let Some(memory) = &self.memory {
1613            let _ = memory.persist(state);
1614        }
1615    }
1616
1617    /// Close out a cancelled turn and say so, as Python's `_cancelled`. The partial
1618    /// exchange is kept: the user stopped the agent, they did not undo it. The phase
1619    /// is `error`; "cancelled" is carried by the trace's `status` and `reason`.
1620    /// Beyond Python, which trims silently: when fitting leaves messages out of a
1621    /// request, the trace gets a `context_trim` event each time the count changes,
1622    /// and the turn says so once (again after a compaction has written a summary).
1623    fn announce_trim(
1624        &self,
1625        sid: &str,
1626        fitted: &Fitted,
1627        budget: u64,
1628        window: &mut TurnWindow<'_>,
1629        emit: &mut impl FnMut(TurnEvent<'_>),
1630    ) {
1631        if fitted.dropped == window.trimmed {
1632            return;
1633        }
1634        window.trimmed = fitted.dropped;
1635        if fitted.dropped == 0 {
1636            return;
1637        }
1638        self.recorder.event(
1639            sid,
1640            "context_trim",
1641            vec![
1642                ("dropped", json!(fitted.dropped)),
1643                ("kept", json!(fitted.messages.len())),
1644                ("budget", json!(budget)),
1645                ("goal_pinned", json!(fitted.pinned)),
1646            ],
1647        );
1648        if !window.trim_announced {
1649            window.trim_announced = true;
1650            emit(TurnEvent::Notice(&trimmed_notice(fitted.dropped)));
1651        }
1652    }
1653
1654    /// Beyond Python: say that the turn was going in circles and record it (a
1655    /// `stall` trace event, since Python has none); the loop then sends the
1656    /// model [`crate::stall::Stall::note`].
1657    fn remind_of_stall(
1658        &self,
1659        found: &crate::stall::Stall,
1660        sid: &str,
1661        emit: &mut impl FnMut(TurnEvent<'_>),
1662    ) {
1663        emit(TurnEvent::Notice(&found.notice()));
1664        let mut fields = vec![
1665            ("shape", json!(found.kind.as_str())),
1666            ("count", json!(found.count)),
1667        ];
1668        if let Some(tool) = &found.tool {
1669            fields.push(("tool", json!(tool)));
1670        }
1671        self.recorder.event(sid, "stall", fields);
1672    }
1673
1674    /// Beyond Python: a `context_age` trace event whenever the number of tool
1675    /// results a request sends aged changes (`crate::memory::sizing::aged_view`).
1676    /// Nothing is said to the user: the session keeps every result whole.
1677    fn announce_age(&self, sid: &str, aged: usize, budget: u64, window: &mut TurnWindow<'_>) {
1678        if aged == window.aged {
1679            return;
1680        }
1681        window.aged = aged;
1682        self.recorder.event(
1683            sid,
1684            "context_age",
1685            vec![("aged", json!(aged)), ("budget", json!(budget))],
1686        );
1687    }
1688
1689    fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
1690        state.phase = AgentPhase::Error;
1691        self.recorder.event(
1692            &state.session_id,
1693            "turn_end",
1694            vec![
1695                ("status", json!("cancelled")),
1696                ("reason", json!("cancelled")),
1697                ("steps", json!(steps)),
1698            ],
1699        );
1700        emit(TurnEvent::Notice(CANCELLED_NOTICE));
1701    }
1702
1703    /// Run a step's tool calls and return their results in call order.
1704    ///
1705    /// Read-only calls may run concurrently with each other; side-effecting calls
1706    /// run sequentially, in the order the model asked for them, after the reads.
1707    /// Every approval is settled first, on this thread, because the gate may
1708    /// prompt a human.
1709    ///
1710    /// Beyond Python, adjacent delegations to specialist sub-agents among the
1711    /// calls left after the reads run at once (`Harness::fan_out`, `[agents]
1712    /// max_parallel`), so a write listed before a delegation still happens first.
1713    /// A batch with any specialty delegation takes this reads-first path whatever
1714    /// the number of reads; `spent` is what the turn has spent so far, for the
1715    /// fan-out's cost cap.
1716    async fn execute_batch(
1717        &self,
1718        calls: &[ToolCall],
1719        sid: &str,
1720        spent: f64,
1721    ) -> Vec<(ToolResult, Usage)> {
1722        let eligible = calls
1723            .iter()
1724            .filter(|call| self.parallel_eligible(call))
1725            .count();
1726        let specialty: Vec<bool> = calls
1727            .iter()
1728            .map(|call| self.is_specialty_delegation(call))
1729            .collect();
1730        let any_specialty = specialty.contains(&true);
1731        if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
1732            // Strictly sequential: each call is resolved and run before the next.
1733            let mut results = Vec::with_capacity(calls.len());
1734            for call in calls {
1735                results.push(if self.cancel.is_cancelled() {
1736                    (not_executed(call, "cancelled"), Usage::default())
1737                } else {
1738                    self.execute_tool(call, sid).await
1739                });
1740            }
1741            return results;
1742        }
1743
1744        let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
1745        let mut may_parallel = Vec::with_capacity(calls.len());
1746        for call in calls {
1747            let (result, parallel) = self.resolve_call(call, sid);
1748            settled.push(result.map(|result| (result, Usage::default())));
1749            may_parallel.push(parallel);
1750        }
1751        let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
1752        let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
1753        let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
1754
1755        if reads.len() > 1 {
1756            let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
1757                let handles: Vec<_> = reads
1758                    .iter()
1759                    .map(|&index| {
1760                        (
1761                            index,
1762                            scope.spawn(move || self.dispatch(&calls[index], sid)),
1763                        )
1764                    })
1765                    .collect();
1766                handles
1767                    .into_iter()
1768                    .map(|(index, handle)| {
1769                        let result = handle
1770                            .join()
1771                            .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
1772                        (index, result)
1773                    })
1774                    .collect()
1775            });
1776            for (index, result) in collected {
1777                settled[index] = Some((result, Usage::default()));
1778            }
1779        } else {
1780            for &index in &reads {
1781                settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1782            }
1783        }
1784        // Between calls, never mid-execution: a tool that started is allowed to finish.
1785        // A run of adjacent specialty delegations goes together; anything else
1786        // (a write, a plain delegation) runs alone and separates them.
1787        let mut next = 0;
1788        while next < writes.len() {
1789            let index = writes[next];
1790            let run_end = writes[next..]
1791                .iter()
1792                .position(|&index| !specialty[index])
1793                .map_or(writes.len(), |offset| next + offset);
1794            if specialty[index] && run_end - next > 1 {
1795                let group: Vec<usize> = writes[next..run_end].to_vec();
1796                let results = if self.cancel.is_cancelled() {
1797                    group
1798                        .iter()
1799                        .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
1800                        .collect()
1801                } else {
1802                    let members: Vec<&ToolCall> =
1803                        group.iter().map(|&index| &calls[index]).collect();
1804                    self.fan_out(&members, sid, spent)
1805                };
1806                for (index, result) in group.into_iter().zip(results) {
1807                    settled[index] = Some(result);
1808                }
1809                next = run_end;
1810            } else {
1811                settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1812                next += 1;
1813            }
1814        }
1815
1816        settled
1817            .into_iter()
1818            .zip(calls)
1819            .map(|(result, call)| {
1820                result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
1821            })
1822            .collect()
1823    }
1824
1825    /// Could this call share a step with its siblings? Decided from the tool alone,
1826    /// never the gate, which may prompt and must be consulted exactly once.
1827    fn parallel_eligible(&self, call: &ToolCall) -> bool {
1828        call.invalid_arguments().is_none()
1829            && self
1830                .registry
1831                .get(&call.name)
1832                .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
1833    }
1834
1835    /// Decide one call without running it: `(settled result, may run in parallel)`.
1836    ///
1837    /// Arguments the provider could not parse are answered here, before the
1838    /// registry, the approval gate, or any tool sees them.
1839    ///
1840    /// Beyond Python, a call answered here is recorded as a `tool_call` event
1841    /// too, with Python's fields, so the trace says why a step's calls never ran
1842    /// (Python records only the calls it dispatches).
1843    pub(crate) fn resolve_call(&self, call: &ToolCall, sid: &str) -> (Option<ToolResult>, bool) {
1844        let settled = |result: ToolResult| {
1845            self.record_tool_call(call, &result, sid);
1846            (Some(result), false)
1847        };
1848        if let Some(raw) = call.invalid_arguments() {
1849            return settled(invalid_arguments_result(call, raw));
1850        }
1851        let Some(tool) = self.registry.get(&call.name) else {
1852            // The registry's own "Unknown tool" answer.
1853            return settled(self.registry.dispatch(call, &self.context));
1854        };
1855        // Under `run --agent`, a call outside the specialty's tools gets the
1856        // registry's refusal, which says so, before the gate is consulted.
1857        if !self.context.scope_allows(&call.name) {
1858            return settled(self.registry.dispatch(call, &self.context));
1859        }
1860        let decision = self.gate.decide(tool.as_ref(), call, &self.context);
1861        if !decision.approved {
1862            return settled(not_executed(call, decision.reason));
1863        }
1864        (None, !tool.side_effecting() && tool.parallel_safe())
1865    }
1866
1867    async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1868        if self.cancel.is_cancelled() {
1869            (not_executed(call, "cancelled"), Usage::default())
1870        } else {
1871            self.dispatch_call(call, sid).await
1872        }
1873    }
1874
1875    /// Run one approved call: a delegation runs its sub-agent here, on this
1876    /// runtime; anything else goes to the registry.
1877    async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1878        let request = match self.delegation(call, &self.context) {
1879            Some(request) => request,
1880            None => return (self.dispatch(call, sid), Usage::default()),
1881        };
1882        let mut span = self.tool_span(call);
1883        let (result, usage) = match request {
1884            Ok(request) => self.delegate(call, request, 1, &self.context).await,
1885            Err(invalid) => (invalid, Usage::default()),
1886        };
1887        span.set(vec![("tool.ok", json!(result.ok))]);
1888        self.tracer.end(span);
1889        self.record_tool_call(call, &result, sid);
1890        (result, usage)
1891    }
1892
1893    /// Run one approved call and record it in the flight recorder.
1894    pub(crate) fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
1895        let mut span = self.tool_span(call);
1896        let result = self.registry.dispatch(call, &self.context);
1897        span.set(vec![("tool.ok", json!(result.ok))]);
1898        self.tracer.end(span);
1899        self.record_tool_call(call, &result, sid);
1900        result
1901    }
1902
1903    /// A `tool_call` span for `call`, as Python's `_dispatch_call` opens.
1904    pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
1905        self.tracer.start(
1906            "tool_call",
1907            vec![
1908                ("tool.name", json!(call.name)),
1909                ("gen_ai.tool.name", json!(call.name)),
1910            ],
1911        )
1912    }
1913
1914    pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1915        self.recorder.event(
1916            sid,
1917            "tool_call",
1918            vec![
1919                ("tool", json!(call.name)),
1920                ("ok", json!(result.ok)),
1921                ("arguments", Value::Object(call.arguments.clone())),
1922                ("error", json!(result.error)),
1923            ],
1924        );
1925        self.record_repair(call, result, sid);
1926    }
1927
1928    /// Beyond Python: note a call whose JSON-string arguments the registry repaired
1929    /// (`tools::repair_arguments`). The call itself is recorded as the model sent it.
1930    pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1931        if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
1932            self.recorder.event(
1933                sid,
1934                "tool_args_repaired",
1935                vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
1936            );
1937        }
1938    }
1939
1940    /// Beyond Python (ADR 0006): repair each call whose arguments did not parse
1941    /// but do once every closer that matches nothing is dropped
1942    /// (`broken_json::drop_unmatched_closers`). Unlike the JSON-string repair, the
1943    /// repaired arguments replace the raw text on the call itself, since that text
1944    /// is no call at all: the history, the approval gate, the tool, and replay on
1945    /// resume then all see the same call. A `tool_args_repaired` event records
1946    /// what was dropped. Returns the note each repaired call's result gets, by id.
1947    pub(crate) fn repair_broken_calls(
1948        &self,
1949        calls: &mut [ToolCall],
1950        sid: &str,
1951    ) -> HashMap<String, String> {
1952        let mut notes = HashMap::new();
1953        for call in calls.iter_mut() {
1954            let Some(raw) = call.invalid_arguments() else {
1955                continue;
1956            };
1957            let Some((arguments, dropped)) = crate::broken_json::drop_unmatched_closers(raw) else {
1958                continue;
1959            };
1960            self.recorder.event(
1961                sid,
1962                "tool_args_repaired",
1963                vec![
1964                    ("tool", json!(call.name)),
1965                    (
1966                        "dropped",
1967                        json!(dropped
1968                            .iter()
1969                            .map(|(at, closer)| json!({"at": at, "char": closer.to_string()}))
1970                            .collect::<Vec<_>>()),
1971                    ),
1972                ],
1973            );
1974            notes.insert(call.id.clone(), repair_note(&dropped));
1975            call.arguments = arguments;
1976        }
1977        notes
1978    }
1979
1980    /// `result` with what the model should know about its call's JSON: the
1981    /// repair's note, for a call [`Harness::repair_broken_calls`] repaired, and,
1982    /// once a tool's arguments have failed to parse twice in a row, advice on
1983    /// sending less (beyond Python; ADR 0006).
1984    pub(crate) fn annotate_broken_json(
1985        &self,
1986        call: &ToolCall,
1987        result: ToolResult,
1988        repairs: &HashMap<String, String>,
1989        streak: &mut BrokenStreak,
1990    ) -> ToolResult {
1991        let mut result = result;
1992        if let Some(note) = repairs.get(&call.id) {
1993            append_note(&mut result, note);
1994        }
1995        if let Some(count) = streak.observe(call) {
1996            let mut advice = format!(
1997                "{count} calls in a row to {} have sent arguments that do not parse. Long, \
1998                 deeply nested arguments break most often: send less in each call.",
1999                call.name
2000            );
2001            if let Some(hint) = self
2002                .registry
2003                .get(&call.name)
2004                .and_then(|tool| tool.retry_hint().map(str::to_owned))
2005            {
2006                advice.push(' ');
2007                advice.push_str(&hint);
2008            }
2009            append_note(&mut result, &advice);
2010        }
2011        result
2012    }
2013
2014    /// Egress-scan tool-call arguments, the other way a secret leaves the harness.
2015    /// Findings are recorded, not acted on; the approval gate stops side effects.
2016    fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
2017        if self.guardrails.egress == EgressMode::Off {
2018            return;
2019        }
2020        for call in calls {
2021            let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
2022            let (report, _) = self.guardrails.inspect_egress(&payload);
2023            if report.flagged() {
2024                self.recorder.event(
2025                    sid,
2026                    "guardrail",
2027                    vec![
2028                        ("stage", json!("egress_tool_args")),
2029                        ("tool", json!(call.name)),
2030                        ("findings", json!(report.summary())),
2031                    ],
2032                );
2033            }
2034        }
2035    }
2036
2037    /// Resolve and run one call.
2038    async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
2039        match self.resolve_call(call, sid) {
2040            (Some(result), _) => (result, Usage::default()),
2041            (None, _) => self.dispatch_call(call, sid).await,
2042        }
2043    }
2044}
2045
2046/// How many calls in a row to each tool have sent arguments that did not parse,
2047/// in one loop's turn (beyond Python; ADR 0006).
2048#[derive(Debug, Default)]
2049pub(crate) struct BrokenStreak(HashMap<String, u32>);
2050
2051impl BrokenStreak {
2052    /// Count `call`: the streak when its arguments did not parse and it is at
2053    /// least the second such call to its tool in a row, else `None`. A call
2054    /// that parsed (or was repaired) ends its tool's streak.
2055    fn observe(&mut self, call: &ToolCall) -> Option<u32> {
2056        let count = self.0.entry(call.name.clone()).or_default();
2057        if call.invalid_arguments().is_none() {
2058            *count = 0;
2059            return None;
2060        }
2061        *count += 1;
2062        (*count >= 2).then_some(*count)
2063    }
2064}
2065
2066/// What the model is told about a call whose broken arguments were repaired.
2067fn repair_note(dropped: &[(usize, char)]) -> String {
2068    let closers: Vec<String> = dropped
2069        .iter()
2070        .map(|(at, closer)| format!("`{closer}` at character {at}"))
2071        .collect();
2072    let noun = if dropped.len() == 1 {
2073        "closer"
2074    } else {
2075        "closers"
2076    };
2077    format!(
2078        "Note: these arguments were not valid JSON. agent86 dropped the unmatched {noun} {}, \
2079         which matched nothing, and ran the call with the rest. Check next time that every \
2080         bracket closes in order.",
2081        closers.join(", ")
2082    )
2083}
2084
2085/// Add `note` to what the model reads of `result`: after its output when the
2086/// call worked, after its error when it failed.
2087fn append_note(result: &mut ToolResult, note: &str) {
2088    let text = if result.ok {
2089        &mut result.content
2090    } else {
2091        result.error.get_or_insert_with(String::new)
2092    };
2093    if !text.is_empty() {
2094        text.push_str("\n\n");
2095    }
2096    text.push_str(note);
2097}
2098
2099/// The observation for a call that was not run.
2100pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
2101    ToolResult {
2102        call_id: call.id.clone(),
2103        name: call.name.clone(),
2104        ok: false,
2105        content: String::new(),
2106        error: Some(format!("Not executed: {reason}.")),
2107        metadata: serde_json::Map::new(),
2108    }
2109}
2110
2111/// Closing attributes for a `model_call` span, as Python's `_model_call_attributes`.
2112fn model_call_attributes(
2113    completion: Option<&crate::types::Completion>,
2114) -> Vec<(&'static str, Value)> {
2115    let Some(completion) = completion else {
2116        return vec![("agent86.completed", json!(false))];
2117    };
2118    let finish = completion
2119        .stop_reason
2120        .as_deref()
2121        .filter(|reason| !reason.is_empty())
2122        .map_or(Value::Null, |reason| json!([reason]));
2123    vec![
2124        ("agent86.completed", json!(true)),
2125        (
2126            "gen_ai.usage.input_tokens",
2127            json!(completion.usage.input_tokens),
2128        ),
2129        (
2130            "gen_ai.usage.output_tokens",
2131            json!(completion.usage.output_tokens),
2132        ),
2133        ("gen_ai.response.finish_reasons", finish),
2134        ("agent86.cost_usd", json!(completion.usage.cost_usd)),
2135        ("agent86.tool_calls", json!(completion.tool_calls.len())),
2136    ]
2137}
2138
2139/// Closing attributes for the `turn` span, read off `state.last_turn`, as Python's
2140/// `_turn_attributes`.
2141fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
2142    let mut attributes = vec![("gen_ai.request.model", json!(model))];
2143    if let Some(summary) = &state.last_turn {
2144        attributes.extend([
2145            ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
2146            ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
2147            ("agent86.cost_usd", json!(summary.cost_usd)),
2148            ("agent86.steps", json!(summary.steps)),
2149            ("agent86.tool_calls", json!(summary.tool_calls)),
2150            ("agent86.duration_s", json!(summary.duration_s)),
2151            (
2152                "agent86.phase",
2153                serde_json::to_value(state.phase).unwrap_or(Value::Null),
2154            ),
2155        ]);
2156    }
2157    attributes
2158}
2159
2160/// Append `step` to the session and add its usage, as Python's `AgentState.record_step`.
2161fn record_step(state: &mut AgentState, step: Step) {
2162    state.usage = state.usage + step.usage;
2163    state.steps.push(step);
2164}
2165
2166fn message(role: Role, content: &str) -> Message {
2167    Message {
2168        role,
2169        content: content.to_owned(),
2170        tool_calls: Vec::new(),
2171        tool_call_id: None,
2172        name: None,
2173    }
2174}
2175
2176/// The observation for a tool call whose arguments were not valid JSON.
2177///
2178/// Its first line is Python's. Beyond Python, the lines after it say where the
2179/// JSON broke (`broken_json::describe`): the first 200 characters Python quotes
2180/// are usually fine, and a model shown only them guesses at what to fix.
2181pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
2182    let preview = truncate_chars(raw, 200);
2183    let mut error = format!(
2184        "invalid JSON in tool arguments: {} could not be parsed. \
2185         Call the tool again with its arguments as a single valid JSON object.",
2186        python_repr(&preview)
2187    );
2188    if let Some(location) = crate::broken_json::describe(raw) {
2189        error.push('\n');
2190        error.push_str(&location);
2191    }
2192    ToolResult {
2193        call_id: call.id.clone(),
2194        name: call.name.clone(),
2195        ok: false,
2196        content: String::new(),
2197        error: Some(error),
2198        metadata: serde_json::Map::new(),
2199    }
2200}
2201
2202/// The text the model observes for `result`. A failure keeps both its error and
2203/// any output, so the model can see what went wrong.
2204pub fn observation(result: &ToolResult) -> String {
2205    if result.ok {
2206        return result.content.clone();
2207    }
2208    let error = result.error.as_deref().unwrap_or_default().trim();
2209    let body = result.content.trim();
2210    match (error.is_empty(), body.is_empty()) {
2211        (false, false) => format!("{error}\n{body}"),
2212        (false, true) => error.to_owned(),
2213        (true, false) => body.to_owned(),
2214        (true, true) => "error".to_owned(),
2215    }
2216}
2217
2218/// The temperature a request sends, beyond Python's fixed 0.0: the specialty's
2219/// own, else its model's provider section's, else 0.0. Summaries keep 0.0.
2220pub(crate) fn request_temperature(provider: &dyn Provider, specialty: Option<f32>) -> f32 {
2221    specialty.or_else(|| provider.temperature()).unwrap_or(0.0)
2222}
2223
2224/// Tool arguments as Python's `json.dumps(..., ensure_ascii=False)`, cut at 160 characters.
2225pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
2226    let text = python_json_dumps(&Value::Object(arguments.clone()), false);
2227    truncate_chars(&text, 160)
2228}
2229
2230/// The one-line summary of a result shown after `[tool] name ->`.
2231pub fn summarize(result: &ToolResult) -> String {
2232    if !result.ok {
2233        let error = result.error.as_deref().unwrap_or_default().trim();
2234        let content = result.content.trim();
2235        let detail = [error, content, "(failed)"]
2236            .into_iter()
2237            .find(|text| !text.is_empty())
2238            .unwrap_or("(failed)");
2239        return format!("error: {}", first_chars(first_line(detail), 160));
2240    }
2241    let content = result.content.trim();
2242    let head = if content.is_empty() {
2243        "(no output)"
2244    } else {
2245        first_line(content)
2246    };
2247    first_chars(head, 160)
2248}
2249
2250/// The first line of `text`, splitting on every boundary Python's `splitlines()` uses.
2251fn first_line(text: &str) -> &str {
2252    let is_break = |c: char| {
2253        matches!(
2254            c,
2255            '\n' | '\r'
2256                | '\u{b}'
2257                | '\u{c}'
2258                | '\u{1c}'
2259                | '\u{1d}'
2260                | '\u{1e}'
2261                | '\u{85}'
2262                | '\u{2028}'
2263                | '\u{2029}'
2264        )
2265    };
2266    text.split(is_break).next().unwrap_or_default()
2267}
2268
2269fn first_chars(text: &str, limit: usize) -> String {
2270    text.chars().take(limit).collect()
2271}
2272
2273/// `text` if it has at most `limit` characters, else its first `limit` and `" ..."`.
2274fn truncate_chars(text: &str, limit: usize) -> String {
2275    if text.chars().count() <= limit {
2276        text.to_owned()
2277    } else {
2278        format!("{} ...", first_chars(text, limit))
2279    }
2280}
2281
2282#[cfg(test)]
2283mod tests {
2284    use super::*;
2285    use serde_json::json;
2286
2287    fn limits() -> LimitsConfig {
2288        LimitsConfig {
2289            max_steps: 2,
2290            max_cost_usd: 1.0,
2291            max_wall_clock_s: 900,
2292            max_consecutive_errors: 1,
2293            max_context_tokens: 0,
2294            max_output_tokens: 8192,
2295            context_reserve_tokens: 4096,
2296            compaction: CompactionMode::Summarize,
2297            parallel_tools: true,
2298            tool_timeout_s: 60,
2299            context_sizing: true,
2300            stall_nudge: true,
2301        }
2302    }
2303
2304    #[test]
2305    fn the_breaker_trips_on_steps_cost_and_error_streaks() {
2306        let mut breaker = CircuitBreaker::new(&limits());
2307        breaker.before_step().unwrap();
2308        breaker.record_step(&Usage::default());
2309        breaker.record_step(&Usage::default());
2310        assert_eq!(
2311            breaker.before_step().unwrap_err().to_string(),
2312            "Circuit tripped: step budget reached (2 steps)"
2313        );
2314
2315        let mut costly = CircuitBreaker::new(&limits());
2316        costly.record_step(&Usage {
2317            cost_usd: 1.25,
2318            ..Usage::default()
2319        });
2320        assert_eq!(
2321            costly.before_step().unwrap_err().to_string(),
2322            "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
2323        );
2324
2325        let mut errors = CircuitBreaker::new(&limits());
2326        errors.record_tool_result(false).unwrap();
2327        errors.record_tool_result(true).unwrap();
2328        errors.record_tool_result(false).unwrap();
2329        assert_eq!(
2330            errors.record_tool_result(false).unwrap_err().to_string(),
2331            "Circuit tripped: aborted after 2 consecutive tool errors"
2332        );
2333    }
2334
2335    fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
2336        ToolResult {
2337            call_id: "c".to_owned(),
2338            name: "t".to_owned(),
2339            ok,
2340            content: content.to_owned(),
2341            error: error.map(str::to_owned),
2342            metadata: serde_json::Map::new(),
2343        }
2344    }
2345
2346    #[test]
2347    fn observations_keep_both_error_and_output() {
2348        assert_eq!(observation(&result(true, "data", None)), "data");
2349        assert_eq!(
2350            observation(&result(false, " out ", Some(" bad "))),
2351            "bad\nout"
2352        );
2353        assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
2354        assert_eq!(observation(&result(false, "", None)), "error");
2355    }
2356
2357    #[test]
2358    fn summaries_show_the_first_line() {
2359        assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
2360        assert_eq!(summarize(&result(true, "  ", None)), "(no output)");
2361        assert_eq!(
2362            summarize(&result(false, "", Some("No such file: x\nmore"))),
2363            "error: No such file: x"
2364        );
2365        assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
2366        assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
2367    }
2368
2369    #[test]
2370    fn previews_use_python_json_and_cut_at_160_characters() {
2371        let Value::Object(short) = json!({"path": "src/main.rs"}) else {
2372            unreachable!()
2373        };
2374        assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
2375
2376        let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
2377            unreachable!()
2378        };
2379        let preview = preview_arguments(&long);
2380        assert!(preview.ends_with(" ..."));
2381        assert_eq!(preview.chars().count(), 164);
2382    }
2383
2384    #[test]
2385    fn invalid_json_is_reported_with_a_python_repr_preview() {
2386        let call = ToolCall {
2387            id: "c1".to_owned(),
2388            name: "read_file".to_owned(),
2389            arguments: serde_json::Map::new(),
2390        };
2391        let result = invalid_arguments_result(&call, "{\"path\": ");
2392        let error = result.error.as_deref().unwrap();
2393        // Python's line first, then where it broke (beyond Python).
2394        assert_eq!(
2395            error.lines().next(),
2396            Some(
2397                "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
2398                 Call the tool again with its arguments as a single valid JSON object."
2399            )
2400        );
2401        assert_eq!(
2402            error.lines().nth(1),
2403            Some(
2404                "The JSON ends at character 9 inside the top-level object, before it is \
2405                 complete: EOF while parsing a value."
2406            )
2407        );
2408        assert!(!result.ok);
2409        assert_eq!(result.call_id, "c1");
2410    }
2411}