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