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